原諒我的抄襲,我只是怕原作者把文件刪了,或者別的問(wèn)題,導(dǎo)致我以后無(wú)法查看,所以自己再寫一遍
源文件鏈接:http://blog.csdn.net/jdsjlzx/article/details/44228935
android圖片壓縮總結(jié)
總結(jié)來(lái)看,圖片有三種存在形式:硬盤上時(shí)是file,網(wǎng)絡(luò)傳輸時(shí)是stream,內(nèi)存中是stream或bitmap,所謂的質(zhì)量壓縮,它其實(shí)只能實(shí)現(xiàn)對(duì)file的影響,你可以把一個(gè)file轉(zhuǎn)成bitmap再轉(zhuǎn)成file,或者直接將一個(gè)bitmap轉(zhuǎn)成file時(shí),這個(gè)最終的file是被壓縮過(guò)的,但是中間的bitmap并沒(méi)有被壓縮(或者說(shuō)幾乎沒(méi)有被壓縮,我不確定),因?yàn)閎igmap在內(nèi)存中的大小是按像素計(jì)算的,也就是width * height,對(duì)于質(zhì)量壓縮,并不會(huì)改變圖片的像素,所以就算質(zhì)量被壓縮了,但是bitmap在內(nèi)存的占有率還是沒(méi)變小,但你做成file時(shí),它確實(shí)變小了;
而尺寸壓縮由于是減小了圖片的像素,所以它直接對(duì)bitmap產(chǎn)生了影響,當(dāng)然最終的file也是相對(duì)的變小了;
最后把自己總結(jié)的工具類貼出來(lái):
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
/**
* Image compress factory class
*
* @author
*
*/
public class ImageFactory {
/**
* Get bitmap from specified image path
*
* @param imgPath
* @return
*/
public Bitmap getBitmap(String imgPath) {
// Get bitmap through image path
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;
newOpts.inPurgeable = true;
newOpts.inInputShareable = true;
// Do not compress
newOpts.inSampleSize = 1;
newOpts.inPreferredConfig = Config.RGB_565;
return BitmapFactory.decodeFile(imgPath, newOpts);
}
/**
* Store bitmap into specified image path
*
* @param bitmap
* @param outPath
* @throws FileNotFoundException
*/
public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
FileOutputStream os = new FileOutputStream(outPath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
/**
* Compress image by pixel, this will modify image width/height.
* Used to get thumbnail
*
* @param imgPath image path
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @return
*/
public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開始讀入圖片,此時(shí)把options.inJustDecodeBounds 設(shè)回true,即只讀邊不讀內(nèi)容
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Config.RGB_565;
// Get bitmap info, but notice that bitmap is null now
Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 想要縮放的目標(biāo)尺寸
float hh = pixelH;// 設(shè)置高度為240f時(shí),可以明顯看到圖片縮小了
float ww = pixelW;// 設(shè)置寬度為120f,可以明顯看到圖片縮小了
// 縮放比。由于是固定比例縮放,只用高或者寬其中一個(gè)數(shù)據(jù)進(jìn)行計(jì)算即可
int be = 1;//be=1表示不縮放
if (w > h && w > ww) {//如果寬度大的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//設(shè)置縮放比例
// 開始?jí)嚎s圖片,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
// 壓縮好比例大小后再進(jìn)行質(zhì)量壓縮
// return compress(bitmap, maxSize); // 這里再進(jìn)行質(zhì)量壓縮的意義不大,反而耗資源,刪除
return bitmap;
}
/**
* Compress image by size, this will modify image width/height.
* Used to get thumbnail
*
* @param image
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @return
*/
public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, os);
if( os.toByteArray().length / 1024>1024) {//判斷如果圖片大于1M,進(jìn)行壓縮避免在生成圖片(BitmapFactory.decodeStream)時(shí)溢出
os.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, os);//這里壓縮50%,把壓縮后的數(shù)據(jù)存放到baos中
}
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//開始讀入圖片,此時(shí)把options.inJustDecodeBounds 設(shè)回true了
newOpts.inJustDecodeBounds = true;
newOpts.inPreferredConfig = Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
float hh = pixelH;// 設(shè)置高度為240f時(shí),可以明顯看到圖片縮小了
float ww = pixelW;// 設(shè)置寬度為120f,可以明顯看到圖片縮小了
//縮放比。由于是固定比例縮放,只用高或者寬其中一個(gè)數(shù)據(jù)進(jìn)行計(jì)算即可
int be = 1;//be=1表示不縮放
if (w > h && w > ww) {//如果寬度大的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0) be = 1;
newOpts.inSampleSize = be;//設(shè)置縮放比例
//重新讀入圖片,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
is = new ByteArrayInputStream(os.toByteArray());
bitmap = BitmapFactory.decodeStream(is, null, newOpts);
//壓縮好比例大小后再進(jìn)行質(zhì)量壓縮
// return compress(bitmap, maxSize); // 這里再進(jìn)行質(zhì)量壓縮的意義不大,反而耗資源,刪除
return bitmap;
}
/**
* Compress by quality, and generate image to the path specified
*
* @param image
* @param outPath
* @param maxSize target will be compressed to be smaller than this size.(kb)
* @throws IOException
*/
public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 100;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Compress by loop
while ( os.toByteArray().length / 1024 > maxSize) {
// Clean up os
os.reset();
// interval 10
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
// Generate compressed image file
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
fos.flush();
fos.close();
}
/**
* Compress by quality, and generate image to the path specified
*
* @param imgPath
* @param outPath
* @param maxSize target will be compressed to be smaller than this size.(kb)
* @param needsDelete Whether delete original file after compress
* @throws IOException
*/
public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
compressAndGenImage(getBitmap(imgPath), outPath, maxSize);
// Delete original file
if (needsDelete) {
File file = new File (imgPath);
if (file.exists()) {
file.delete();
}
}
}
/**
* Ratio and generate thumb to the path specified
*
* @param image
* @param outPath
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @throws FileNotFoundException
*/
public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
Bitmap bitmap = ratio(image, pixelW, pixelH);
storeImage( bitmap, outPath);
}
/**
* Ratio and generate thumb to the path specified
*
* @param image
* @param outPath
* @param pixelW target pixel of width
* @param pixelH target pixel of height
* @param needsDelete Whether delete original file after compress
* @throws FileNotFoundException
*/
public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
storeImage( bitmap, outPath);
// Delete original file
if (needsDelete) {
File file = new File (imgPath);
if (file.exists()) {
file.delete();
}
}
}
}
如果上面的工具類不滿足你,那么看看下面的方法。
一、圖片質(zhì)量壓縮
/**
* 質(zhì)量壓縮方法
*
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中
int options = 90;
while (baos.toByteArray().length / 1024 > 100) { // 循環(huán)判斷如果壓縮后圖片是否大于100kb,大于繼續(xù)壓縮
baos.reset(); // 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數(shù)據(jù)存放到baos中
options -= 10;// 每次都減少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮后的數(shù)據(jù)baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數(shù)據(jù)生成圖片
return bitmap;
}
二、按比例大小壓縮 (路徑獲取圖片)
/**
* 圖片按比例大小壓縮方法
*
* @param srcPath (根據(jù)路徑獲取圖片并壓縮)
* @return
*/
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開始讀入圖片,此時(shí)把options.inJustDecodeBounds 設(shè)回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此時(shí)返回bm為空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 現(xiàn)在主流手機(jī)比較多是800*480分辨率,所以高和寬我們?cè)O(shè)置為
float hh = 800f;// 這里設(shè)置高度為800f
float ww = 480f;// 這里設(shè)置寬度為480f
// 縮放比。由于是固定比例縮放,只用高或者寬其中一個(gè)數(shù)據(jù)進(jìn)行計(jì)算即可
int be = 1;// be=1表示不縮放
if (w > h && w > ww) {// 如果寬度大的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {// 如果高度高的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 設(shè)置縮放比例
// 重新讀入圖片,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);// 壓縮好比例大小后再進(jìn)行質(zhì)量壓縮
}
三、按比例大小壓縮 (Bitmap)
/**
* 圖片按比例大小壓縮方法
*
* @param image (根據(jù)Bitmap圖片壓縮)
* @return
*/
public static Bitmap compressScale(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// 判斷如果圖片大于1M,進(jìn)行壓縮避免在生成圖片(BitmapFactory.decodeStream)時(shí)溢出
if (baos.toByteArray().length / 1024 > 1024) {
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 這里壓縮50%,把壓縮后的數(shù)據(jù)存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開始讀入圖片,此時(shí)把options.inJustDecodeBounds 設(shè)回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
Log.i(TAG, w + "---------------" + h);
// 現(xiàn)在主流手機(jī)比較多是800*480分辨率,所以高和寬我們?cè)O(shè)置為
// float hh = 800f;// 這里設(shè)置高度為800f
// float ww = 480f;// 這里設(shè)置寬度為480f
float hh = 512f;
float ww = 512f;
// 縮放比。由于是固定比例縮放,只用高或者寬其中一個(gè)數(shù)據(jù)進(jìn)行計(jì)算即可
int be = 1;// be=1表示不縮放
if (w > h && w > ww) {// 如果寬度大的話根據(jù)寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) { // 如果高度高的話根據(jù)高度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be; // 設(shè)置縮放比例
// newOpts.inPreferredConfig = Config.RGB_565;//降低圖片從ARGB888到RGB565
// 重新讀入圖片,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
return compressImage(bitmap);// 壓縮好比例大小后再進(jìn)行質(zhì)量壓縮
//return bitmap;
}
分享個(gè)按照?qǐng)D片尺寸壓縮:
public static void compressPicture(String srcPath, String desPath) {
FileOutputStream fos = null;
BitmapFactory.Options op = new BitmapFactory.Options();
// 開始讀入圖片,此時(shí)把options.inJustDecodeBounds 設(shè)回true了
op.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
op.inJustDecodeBounds = false;
// 縮放圖片的尺寸
float w = op.outWidth;
float h = op.outHeight;
float hh = 1024f;//
float ww = 1024f;//
// 最長(zhǎng)寬度或高度1024
float be = 1.0f;
if (w > h && w > ww) {
be = (float) (w / ww);
} else if (w < h && h > hh) {
be = (float) (h / hh);
}
if (be <= 0) {
be = 1.0f;
}
op.inSampleSize = (int) be;// 設(shè)置縮放比例,這個(gè)數(shù)字越大,圖片大小越小.
// 重新讀入圖片,注意此時(shí)已經(jīng)把options.inJustDecodeBounds 設(shè)回false了
bitmap = BitmapFactory.decodeFile(srcPath, op);
int desWidth = (int) (w / be);
int desHeight = (int) (h / be);
bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
try {
fos = new FileOutputStream(desPath);
if (bitmap != null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
需要注意兩個(gè)問(wèn)題:
一、調(diào)用getDrawingCache()前先要測(cè)量,否則的話得到的bitmap為null,這個(gè)我在OnCreate()、OnStart()、OnResume()方法里都試驗(yàn)過(guò)。
二、當(dāng)調(diào)用bitmap.compress(CompressFormat.JPEG, 100, fos);保存為圖片時(shí)發(fā)現(xiàn)圖片背景為黑色,如下圖:
這時(shí)只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下圖:
在實(shí)際開發(fā)中,有時(shí)候我們需求將文件轉(zhuǎn)換為字符串,然后作為參數(shù)進(jìn)行上傳。
必備工具類圖片bitmap轉(zhuǎn)成字符串string與String字符串轉(zhuǎn)換為bitmap圖片格式
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
/**
*
*
* 功能描述:Android開發(fā)之常用必備工具類圖片bitmap轉(zhuǎn)成字符串string與String字符串轉(zhuǎn)換為bitmap圖片格式
*/
public class BitmapAndStringUtils {
/**
* 圖片轉(zhuǎn)成string
*
* @param bitmap
* @return
*/
public static String convertIconToString(Bitmap bitmap)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] appicon = baos.toByteArray();// 轉(zhuǎn)為byte數(shù)組
return Base64.encodeToString(appicon, Base64.DEFAULT);
}
/**
* string轉(zhuǎn)成bitmap
*
* @param st
*/
public static Bitmap convertStringToIcon(String st)
{
// OutputStream out;
Bitmap bitmap = null;
try
{
// out = new FileOutputStream("/sdcard/aa.jpg");
byte[] bitmapArray;
bitmapArray = Base64.decode(st, Base64.DEFAULT);
bitmap =
BitmapFactory.decodeByteArray(bitmapArray, 0,
bitmapArray.length);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
return bitmap;
}
catch (Exception e)
{
return null;
}
}
}
如果你的圖片是File文件,可以用下面代碼:
/**
* 圖片文件轉(zhuǎn)換為指定編碼的字符串
*
* @param imgFile 圖片文件
*/
public static String file2String(File imgFile) {
InputStream in = null;
byte[] data = null;
//讀取圖片字節(jié)數(shù)組
try{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e){
e.printStackTrace();
}
//對(duì)字節(jié)數(shù)組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
String result = encoder.encode(data);
return result;//返回Base64編碼過(guò)的字節(jié)數(shù)組字符串
}