根據網上找的資料和自己用到的地方進行修改的圖片壓縮工具類,有什麼不對的地方請見諒,源碼如下:
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();
}
}
}
}
}