package com.eighteengray.commonutillibrary;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
/**
* 图像处理相关工具类
*/
public class ImageUtils
{
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int TOP = 3;
public static final int BOTTOM = 4;
public static String bitNametime;
//拍照相关
/**
* 调用系统拍照
*
* @param activity
*/
public static void takeCamera(Activity activity)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
activity.startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);
}
/**
* 调用系统相册
*
* @param activity
*/
public static void takePhoto(Activity activity)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activity.startActivityForResult(intent, 2);
}
/**
* 调用系统裁剪
*
* @param aty
* @param uri
* @param imagePath
*/
public static void takeCut(Activity aty, Uri uri, String imagePath)
{
File f = new File(imagePath);
if (!f.exists())
{
File parentFile = f.getParentFile();
if (!parentFile.exists())
{
parentFile.mkdirs();
}
try
{
f.createNewFile();
} catch (IOException e)
{
e.printStackTrace();
}
}
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// crop为true是设置在开启的intent中设置显示的view可以剪裁
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX,outputY 是剪裁图片的宽高
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.fromFile(new File(imagePath)));// 保存到原文件
intent.putExtra("outputFormat", "JPEG");// 返回格式
aty.startActivityForResult(intent, 3);
}
/**
* 在activityOnResult中拿到图片
*
* @param data 在onActivityResult中拿到的Intent
* @param context
* @return
*/
public static Bitmap getDataOnResult(Intent data, Context context)
{
Bitmap bitmap = null;
Uri uri = data.getData();
ContentResolver cr = context.getContentResolver();
try
{
bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
return bitmap;
}
//保存图片
/**
* 保存图像到指定路径
*/
public static void saveBitmap(Bitmap bitmap, String path, String name)
{
if (bitmap != null)
{
File file = FileUtils.createFile(path, name);
try
{
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
//加载图像
/**
* 从路径中加载图像,原来的数据大小,原来的长宽
*/
public static Bitmap getBitmapFromPath(String imagePath)
{
byte[] data = new byte[0];
try
{
data = getBytesFromInputStream(new URL(imagePath).openStream());
} catch (IOException e)
{
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}
public static byte[] getBytesFromInputStream(InputStream is) throws IOException
{
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // 用数据装
int len = -1;
while ((len = is.read(buffer)) != -1)
{
outstream.write(buffer, 0, len);
}
outstream.close();
// 关闭流一定要记得。
return outstream.toByteArray();
}
/**
* 从路径中加载图像,指定图片长宽
*/
public static Bitmap getBitmapFromPath(String imagePath, int reqWidth, int reqHeight)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);// 读取图片长宽
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
Bitmap resultBitmap = BitmapFactory.decodeFile(imagePath, options);
return resultBitmap;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
final int width = options.outWidth;
final int height = options.outHeight;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
//使用需要的宽高的最大值来计算比率
final int suitedValue = reqHeight > reqWidth ? reqHeight : reqWidth;
final int heightRatio = Math.round((float) height / (float) suitedValue);
final int widthRatio = Math.round((float) width / (float) suitedValue);
inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;//用最大
}
return inSampleSize;
}
/**
* 从Resources中加载图片,指定图片长宽
*/
public static Bitmap getBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight)
{
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options); // 读取图片长宽
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 计算inSampleSize
options.inJustDecodeBounds = false;
Bitmap resultBitmap = BitmapFactory.decodeResource(res, resId, options); // 载入一个稍大的缩略图
return resultBitmap;
}
//图片处理
/**
* 压缩图像到指定大小
*/
public Bitmap compressBitmap(Bitmap bitmap, int maxSize) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > maxSize)
{
baos.reset();
options -= 10;
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
return bitmap;
}
/**
* 把传入的图片等比例缩放
*/
public static Bitmap zoomBitmap(Bitmap bitmap, double width, double height)
{
Bitmap zoomBitmap = null;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidht, scaleHeight);
try
{
zoomBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
} catch (Exception e)
{
e.printStackTrace();
}
return zoomBitmap;
}
/**
* 从原图像上截取指定大小的图像
*/
public static Bitmap cutBitmap(Bitmap bitmap, int x, int y, int width, int height)
{
return Bitmap.createBitmap(bitmap, x, y, width, height);
}
/**
* 获取视频缩略图
*/
public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind)
{
Bitmap bitmap = null;
bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
/**
* 图像旋转
*/
public static Bitmap bitmapRotate(Bitmap bitmap, int rotateAngle)
{
Matrix matrix = new Matrix();
matrix.setRotate(rotateAngle, (float) bitmap.getWidth(), (float) bitmap.getHeight());
float targetX, targetY;
if (rotateAngle == 90)
{
targetX = bitmap.getHeight();
targetY = 0;
} else
{
targetX = bitmap.getHeight();
targetY = bitmap.getWidth();
}
final float[] values = new float[9];
matrix.getValues(values);
float x1 = values[Matrix.MTRANS_X];
float y1 = values[Matrix.MTRANS_Y];
matrix.postTranslate(targetX - x1, targetY - y1);
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getWidth(), Config.ARGB_8888);
Paint paint = new Paint();
Canvas canvas = new Canvas(newBitmap);
canvas.drawBitmap(bitmap, matrix, paint);
return newBitmap;
}
/**
* 圆角图片
*/
public static Bitmap bitmapRoundCorner(Bitmap bitmap, int pixels)
{
Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(roundCornerBitmap);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); //两个绘制取交集就可以画出圆角图像
canvas.drawBitmap(bitmap, rect, rect, paint);
return roundCornerBitmap;
}
/**
* 转变为灰度图
*/
public static Bitmap grayBitmap(Bitmap bitmap)
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap grayBitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
Canvas c = new Canvas(grayBitmap);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
paint.setColorFilter(cf); //这里用paint的ColorFilter做颜色过滤
c.drawBitmap(bitmap, 0, 0, paint);
return grayBitmap;
}
/**
* 图像上添加水印,添加的是图像
*/
public static Bitmap watermarkWithBmp(Bitmap bitmap, Bitmap mark, int x, int y)
{
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap newb = Bitmap.createBitmap(w, h, Config.RGB_565);
Canvas cv = new Canvas(newb);
cv.drawBitmap(bitmap, 0, 0, null);
cv.save(Canvas.ALL_SAVE_FLAG);
cv.drawBitmap(mark, x, y, null); //系需要先画一幅图,再画另一幅图就可以
cv.restore();//存储
return newb;
}
/**
* 图像上添加水印,添加的是文字
*/
public static Bitmap watermarkWithText(Bitmap bitmap, String text, int x, int y, int size, int color)
{
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap newb = Bitmap.createBitmap(w, h, Config.RGB_565);
Canvas cv = new Canvas(newb);
cv.drawBitmap(bitmap, 0, 0, null);
Paint p = new Paint();
p.setARGB(250, 255, 255, 255);
p.setAntiAlias(true);//去除锯齿
p.setFilterBitmap(true);//对位图进行滤波处理
p.setTextSize(size);
cv.drawText(text, x, y, p); //也是先画原图,再画文字
cv.save(Canvas.ALL_SAVE_FLAG);
cv.restore();
return newb;
}
}