android圖片壓縮工具類分享
本文實(shí)例為大家分享了android圖片壓縮工具類的具體代碼,供大家參考,具體內(nèi)容如下
import java.io.BufferedOutputStream;
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 java.io.InputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.net.Uri;
import android.widget.Toast;
/**
* 圓形圖片工具類
*
* @author SKLM
*
*/
public class ImageViewTool {
/**
* 我們先看下質(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 = 100;
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;
}
/**
* 圖片按比例大小壓縮方法(根據(jù)路徑獲取圖片并壓縮)
*
* @param srcPath
* @return
*/
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開(kāi)始讀入圖片,此時(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ì)量壓縮
}
/**
* 圖片按比例大小壓縮方法(根據(jù)Bitmap圖片壓縮)
*
* @param image
* @return
*/
public static Bitmap comp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if (baos.toByteArray().length / 1024 > 1024) {// 判斷如果圖片大于1M,進(jìn)行壓縮避免在生成圖片(BitmapFactory.decodeStream)時(shí)溢出
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 30, baos);// 這里壓縮50%,把壓縮后的數(shù)據(jù)存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開(kāi)始讀入圖片,此時(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;
// 現(xiàn)在主流手機(jī)比較多是800*480分辨率,所以高和寬我們?cè)O(shè)置為
float hh = 150f;// 這里設(shè)置高度為800f
float ww = 150f;// 這里設(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了
isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
return compressImage(bitmap);// 壓縮好比例大小后再進(jìn)行質(zhì)量壓縮
}
public static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 按原比例壓縮圖片到指定尺寸
*
* @param context
* @param inputUri
* @param outputUri
* @param maxLenth
* 最長(zhǎng)邊長(zhǎng)
*/
public static void reducePicture(Context context, Uri inputUri,
Uri outputUri, int maxLenth, int compress) {
Options options = new Options();
options.inJustDecodeBounds = true;
InputStream is = null;
try {
is = context.getContentResolver().openInputStream(inputUri);
BitmapFactory.decodeStream(is, null, options);
is.close();
int sampleSize = 1;
int longestSide = 0;
int longestSideLenth = 0;
if (options.outWidth > options.outHeight) {
longestSideLenth = options.outWidth;
longestSide = 0;
} else {
longestSideLenth = options.outHeight;
longestSide = 1;
}
if (longestSideLenth > maxLenth) {
sampleSize = longestSideLenth / maxLenth;
}
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize;
is = context.getContentResolver().openInputStream(inputUri);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
is.close();
if (bitmap == null) {
Toast.makeText(context, "圖片獲取失敗,請(qǐng)確認(rèn)您的存儲(chǔ)卡是否正常",
Toast.LENGTH_SHORT).show();
return;
}
Bitmap srcBitmap = bitmap;
float scale = 0;
if (longestSide == 0) {
scale = (float) maxLenth / (float) (srcBitmap.getWidth());
} else {
scale = (float) maxLenth / (float) (srcBitmap.getHeight());
}
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
// 如果尺寸不變會(huì)返回本身,所以需要判斷是否是統(tǒng)一引用來(lái)確定是否需要回收
if (srcBitmap != bitmap) {
srcBitmap.recycle();
srcBitmap = null;
}
saveBitmapToUri(bitmap, outputUri, compress);
bitmap.recycle();
bitmap = null;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static boolean saveBitmapToUri(Bitmap bitmap, Uri uri, int compress)
throws IOException {
File file = new File(uri.getPath());
if (file.exists()) {
if (file.delete()) {
if (!file.createNewFile()) {
return false;
}
}
}
BufferedOutputStream outStream = new BufferedOutputStream(
new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, compress, outStream);
outStream.flush();
outStream.close();
return true;
}
}
接下來(lái)看看第二個(gè)寫(xiě)法壓縮圖片的工具類,如下
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 java.sql.Date;
import java.text.SimpleDateFormat;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Environment;
/**
* 圖像壓縮工廠類
*
* @author
*
*/
public class ImageFactory {
/**
* 從指定的圖像路徑獲取位圖
*
* @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);
}
/**
* 壓縮圖片(質(zhì)量壓縮)
*
* @param bitmap
*/
public static File compressImage(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 500) { // 循環(huán)判斷如果壓縮后圖片是否大于500kb,大于繼續(xù)壓縮
baos.reset();// 重置baos即清空baos
options -= 10;// 每次都減少10
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數(shù)據(jù)存放到baos中
long length = baos.toByteArray().length;
}
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(System.currentTimeMillis());
String filename = format.format(date);
File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
recycleBitmap(bitmap);
return file;
}
public static void recycleBitmap(Bitmap... bitmaps) {
if (bitmaps == null) {
return;
}
for (Bitmap bm : bitmaps) {
if (null != bm && !bm.isRecycled()) {
bm.recycle();
}
}
}
/**
* 將位圖存儲(chǔ)到指定的圖像路徑中
*
* @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);
}
/**
* 通過(guò)像素壓縮圖像,這將改變圖像的寬度/高度。用于獲取縮略圖
*
*
* @param imgPath
* image path
* @param pixelW
* 目標(biāo)寬度像素
* @param pixelH
* 高度目標(biāo)像素
* @return
*/
public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開(kāi)始讀入圖片,此時(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è)置縮放比例
// 開(kāi)始?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;
}
/**
* 壓縮圖像的大小,這將修改圖像寬度/高度。用于獲取縮略圖
*
*
* @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();
// 開(kāi)始讀入圖片,此時(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;
}
/**
* 按質(zhì)量壓縮,并將圖像生成指定的路徑
*
* @param image
* @param outPath
* @param maxSize
* 目標(biāo)將被壓縮到小于這個(gè)大?。↘B)。
* @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();
}
/**
* 按質(zhì)量壓縮,并將圖像生成指定的路徑
*
* @param imgPath
* @param outPath
* @param maxSize
* 目標(biāo)將被壓縮到小于這個(gè)大?。↘B)。
* @param needsDelete
* 是否壓縮后刪除原始文件
* @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();
}
}
}
/**
* 比例和生成拇指的路徑指定
*
* @param image
* @param outPath
* @param pixelW
* 目標(biāo)寬度像素
* @param pixelH
* 高度目標(biāo)像素
* @throws FileNotFoundException
*/
public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH)
throws FileNotFoundException {
Bitmap bitmap = ratio(image, pixelW, pixelH);
storeImage(bitmap, outPath);
}
/**
* 比例和生成拇指的路徑指定
*
* @param image
* @param outPath
* @param pixelW
* 目標(biāo)寬度像素
* @param pixelH
* 高度目標(biāo)像素
* @param needsDelete
* 是否壓縮后刪除原始文件
* @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();
}
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android實(shí)現(xiàn)簡(jiǎn)易計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)簡(jiǎn)易計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06
設(shè)置界面開(kāi)發(fā)Preference Library數(shù)據(jù)重建機(jī)制詳解
這篇文章主要為大家介紹了設(shè)置界面開(kāi)發(fā)利器Preference Library數(shù)據(jù)重建機(jī)制詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
Android開(kāi)發(fā)之時(shí)間日期操作實(shí)例
這篇文章主要介紹了Android開(kāi)發(fā)之時(shí)間日期操作,是Android程序開(kāi)發(fā)中常見(jiàn)的一個(gè)功能,需要的朋友可以參考下2014-08-08
Android Drawerlayout實(shí)現(xiàn)側(cè)滑菜單效果
這篇文章主要為大家詳細(xì)介紹了Android Drawerlayout實(shí)現(xiàn)側(cè)滑菜單效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
android開(kāi)發(fā)修改狀態(tài)欄背景色和圖標(biāo)顏色的示例
本篇文章主要介紹了android開(kāi)發(fā)修改狀態(tài)欄背景色和圖標(biāo)顏色的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Android性能優(yōu)化之plt?hook與native線程監(jiān)控詳解
這篇文章主要為大家介紹了Android性能優(yōu)化之plt?hook與native線程監(jiān)控詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Android RecyclerView詳解之實(shí)現(xiàn) ListView GridView瀑布流效果
RecyclerView 是Android L版本中新添加的一個(gè)用來(lái)取代ListView的SDK,它的靈活性與可替代性比listview更好2016-07-07
android屏蔽按鈕連續(xù)點(diǎn)擊的示例代碼
這篇文章主要介紹了android屏蔽按鈕連續(xù)點(diǎn)擊的示例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
HorizontalScrollView水平滾動(dòng)控件使用方法詳解
這篇文章主要為大家詳細(xì)介紹了HorizontalScrollView水平滾動(dòng)控件的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08

