根据网上找的资料和自己用到的地方进行修改的图片压缩工具类,有什么不对的地方请见谅,源码如下:
public final class ImageTools {
/**
* Transfer drawable to bitmap
*
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
/**
* Bitmap to drawable
*
* @param bitmap
* @return
*/
public static Drawable bitmapToDrawable(Bitmap bitmap) {
return new BitmapDrawable(bitmap);
}
/**
* Input stream to bitmap
*
* @param inputStream
* @return
* @throws Exception
*/
public static Bitmap inputStreamToBitmap(InputStream inputStream)
throws Exception {
return BitmapFactory.decodeStream(inputStream);
}
/**
* Byte transfer to bitmap
*
* @param byteArray
* @return
*/
public static Bitmap byteToBitmap(byte[] byteArray) {
if (byteArray.length != 0) {
return BitmapFactory
.decodeByteArray(byteArray, 0, byteArray.length);
} else {
return null;
}
}
/**
* Byte transfer to drawable
*
* @param byteArray
* @return
*/
public static Drawable byteToDrawable(byte[] byteArray) {
ByteArrayInputStream ins = null;
if (byteArray != null) {
ins = new ByteArrayInputStream(byteArray);
}
return Drawable.createFromStream(ins, null);
}
/**
* Bitmap transfer to bytes
*
* @param bm
* @return
*/
public static byte[] bitmapToBytes(Bitmap bm) {
byte[] bytes = null;
if (bm != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
bytes = baos.toByteArray();
}
return bytes;
}
/**
* Drawable transfer to bytes
*
* @param drawable
* @return
*/
public static byte[] drawableToBytes(Drawable drawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
byte[] bytes = bitmapToBytes(bitmap);
;
return bytes;
}
/**
* Base64 to byte[]
*/
public static byte[] base64ToBytes(String base64) throws IOException {
byte[] bytes = Base64.decode(base64, 1);
return bytes;
}
// /**
// * Byte[] to base64
// */
// public static String bytesToBase64(byte[] bytes) {
// String base64 = Base64.encodeToString(bytes, Base64.NO_WRAP);
// return base64;
// }
/**
* Byte[] to base64
*/
public static String bytesToBase64(byte[] bytes) {
String base64 = Base64.encodeToString(bytes, 1);
return base64;
}
/**
* 将bitmap转换成base64字符串
*
* @param bitmap
* @return base64 字符串
*/
public static String bitmaptoString(Bitmap bitmap, int bitmapQuality) {
// 将Bitmap转换成字符串
String string = null;
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, bitmapQuality, bStream);
byte[] bytes = bStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
return string;
}
/**
* 将base64转换成bitmap图片
*
* @param string base64字符串
* @return bitmap
*/
public static Bitmap stringtoBitmap(String string) {
// 将字符串转换成Bitmap类型
Bitmap bitmap = null;
try {
byte[] bitmapArray;
bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 质量压缩方法
*
* @param image 将要被压缩的图片
* @return bitmap压缩后的图片
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10;
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
/**
* 质量压缩方法
*
* @param image 将要被压缩的图片
* @return baos 压缩后图片输出流
*/
public static ByteArrayOutputStream compress(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length / 1024 > 300) {
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10;
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return baos;
}
/**
* 根据bitmap压缩图片质量
*
* @param bitmap 未压缩的bitmap
* @return 压缩后的bitmap
*/
public static Bitmap cQuality(Bitmap bitmap) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int beginRate = 100;
//第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
while (bOut.size() / 1024 > 100) { //如果压缩后大于100Kb,则提高压缩率,重新压缩
beginRate -= 10;
bOut.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
}
ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
if (newBitmap != null) {
return newBitmap;
} else {
return bitmap;
}
}
public static void imageZoom(Bitmap bitmap) {
//图片允许最大空间 单位:KB
double maxSize = 400.00;
//将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
//将字节换成KB
double mid = b.length / 1024;
//判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
if (mid > maxSize) {
//获取bitmap大小 是允许最大大小的多少倍
double i = mid / maxSize;
//开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小)
// bitmap = zoomBitmap(bitmap, bitmap.getWidth() / Math.sqrt(i), bitmap.getHeight() / Math.sqrt(i));
}
}
/**
* 图片按比例大小压缩方法(根据路径获取图片并压缩)
*/
public static Bitmap getImage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;// 这里设置高度为800f
float ww = 480f;// 这里设置宽度为480f
// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;// be=1表示不缩放
if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 设置缩放比例
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
}
/**
* 图片按比例大小压缩方法(根据路径获取图片并压缩)
*/
public static ByteArrayOutputStream getByteStream(String srcPath,int angle) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float ww = 800f;// 这里设置宽度为800f
int be = (int) (w / ww);
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 设置缩放比例
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
Bitmap map = rotaingImageView(angle,BitmapFactory.decodeFile(srcPath, newOpts));
bitmap = zoomBitmap(map, w / be, h / be);
return compress(bitmap);// 压缩好比例大小后再进行质量压缩
}
/**
* 图片按比例大小压缩方法(根据图片压缩)
*/
public static ByteArrayOutputStream getBitmap(Bitmap bitmap, int angle) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float ww = 800f;// 这里设置宽度为800f
// 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
// int be = 1;// be=1表示不缩放
// if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
// be = (int) (w / ww);
// } else if (w < h && h > ww) {// 如果高度高的话根据宽度固定大小缩放
// be = (int) (h / ww);
// }
int be = (int) (w / ww);
if (be <= 0)
be = 1;
// newOpts.inSampleSize = be;// 设置缩放比例
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
// bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
bitmap = rotaingImageView(angle, zoomBitmap(bitmap, w / be, h / be));
return compress(bitmap);// 压缩好比例大小后再进行质量压缩
}
/**
* 通过uri获取图片并进行压缩
*/
public static ByteArrayOutputStream getBitmapFormUri(Activity ac, Uri uri, int angle) throws FileNotFoundException, IOException {
InputStream input = ac.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
int originalWidth = onlyBoundsOptions.outWidth;
int originalHeight = onlyBoundsOptions.outHeight;
if ((originalWidth == -1) || (originalHeight == -1))
return null;
//图片分辨率以480x800为标准
// float hh = 800f;//这里设置高度为800f
float ww = 800f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (originalWidth / ww);
} else if (originalWidth < originalHeight && originalHeight > ww) {//如果高度高的话根据宽度固定大小缩放
be = (int) (originalHeight / ww);
}
// int be = (int) (originalWidth / ww);
if (be <= 0)
be = 1;
//比例压缩
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = be;//设置缩放比例
bitmapOptions.inDither = true;//optional
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
input = ac.getContentResolver().openInputStream(uri);
Bitmap bitmap = rotaingImageView(angle, BitmapFactory.decodeStream(input, null, bitmapOptions));
input.close();
return compress(bitmap);//再进行质量压缩
}
/**
* 根据图片uri获取图片旋转角度
* @param context
* @param mImageCaptureUri 图片uri路径
* @return angle 旋转角度
*/
public static int setImage(Context context, Uri mImageCaptureUri) {
// 不管是拍照还是选择图片每张图片都有在数据中存储也存储有对应旋转角度orientation值
// 所以我们在取出图片是把角度值取出以便能正确的显示图片,没有旋转时的效果观看
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(mImageCaptureUri, null, null, null, null);// 根据Uri从数据库中找
int angle = 0;
if (cursor != null) {
cursor.moveToFirst();// 把游标移动到首位,因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了
String filePath = cursor.getString(cursor.getColumnIndex("_data"));// 获取图片路
String orientation = cursor.getString(cursor.getColumnIndex("orientation"));// 获取旋转的角度
cursor.close();
if (orientation != null && !"".equals(orientation)) {
angle = Integer.parseInt(orientation);
}
}
Logs.e("angle:::::::::::" + angle);
return angle;
}
/**
* 读取图片属性:旋转的角度
*
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
Logs.e("degree::::::::" + degree);
return degree;
}
/**
* 旋转图片
*
* @param angle 图片旋转角度
* @param bitmap 原图片
* @return Bitmap旋转后的图片
*/
public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
//旋转图片 动作
Matrix matrix = new Matrix();
// matrix.postRotate(angle);
System.out.println("angle2=" + angle);
matrix.setRotate(angle); // 旋转angle度
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* Create reflection images
*
* @param bitmap
* @return
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w,
h / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2),
Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, h, w, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
/**
* Get rounded corner images
*
* @param bitmap
* @param roundPx 5 10
* @return
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
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 output;
}
/**
* Resize the bitmap
*
* @param bitmap
* @param width
* @param height
* @return
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
/**
* Resize the drawable
*
* @param drawable
* @param w
* @param h
* @return
*/
public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap oldbmp = drawableToBitmap(drawable);
Matrix matrix = new Matrix();
float sx = ((float) w / width);
float sy = ((float) h / height);
matrix.postScale(sx, sy);
Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
matrix, true);
return new BitmapDrawable(newbmp);
}
/**
* Get images from SD card by path and the name of image
*
* @param photoName
* @return
*/
public static Bitmap getPhotoFromSDCard(String path, String photoName) {
Bitmap photoBitmap = BitmapFactory.decodeFile(path + "/" + photoName + ".png");
if (photoBitmap == null) {
return null;
} else {
return photoBitmap;
}
}
/**
* Check the SD card
*
* @return
*/
public static boolean checkSDCardAvailable() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
/**
* Get image from SD card by path and the name of image
*
* @param photoName
* @return
*/
public static boolean findPhotoFromSDCard(String path, String photoName) {
boolean flag = false;
if (checkSDCardAvailable()) {
File dir = new File(path);
if (dir.exists()) {
File folders = new File(path);
File photoFile[] = folders.listFiles();
for (int i = 0; i < photoFile.length; i++) {
String fileName = photoFile[i].getName().split("\\.")[0];
if (fileName.equals(photoName)) {
flag = true;
}
}
} else {
flag = false;
}
// File file = new File(path + "/" + photoName + ".jpg" );
// if (file.exists()) {
// flag = true;
// }else {
// flag = false;
// }
} else {
flag = false;
}
return flag;
}
/**
* Save image to the SD card
*
* @param photoBitmap
* @param photoName
* @param path
*/
public static void savePhotoToSDCard(Bitmap photoBitmap, String path, String photoName) {
if (checkSDCardAvailable()) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File photoFile = new File(path, photoName + ".png");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(photoFile);
if (photoBitmap != null) {
if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
fileOutputStream.flush();
// fileOutputStream.close();
}
}
} catch (FileNotFoundException e) {
photoFile.delete();
e.printStackTrace();
} catch (IOException e) {
photoFile.delete();
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Delete the image from SD card
*
* @param path file:///sdcard/temp.jpg
*/
public static void deleteAllPhoto(String path) {
if (checkSDCardAvailable()) {
File folder = new File(path);
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
}
public static void deletePhotoAtPathAndName(String path, String fileName) {
if (checkSDCardAvailable()) {
File folder = new File(path);
File[] files = folder.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].getName().split("\\.")[0].equals(fileName)) {
files[i].delete();
}
}
}
}
}