1、權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2、將圖片轉化爲Bitmap
第一種:返回項目Resources中圖片 Bitmap
// 返回項目中圖片 bitmap
private Bitmap imgToBitmap(){
Bitmap bitmap = BitmapFactory.decodeResource(this.getApplication().getResources(), R.mipmap.imgbitmapio);
return bitmap;
}
第二種:從本地獲取圖片(SAVE_REAL_PATH+”testImage/chen.jpeg”這是本地圖片路徑)
private Bitmap imgToBitmap(){
FileInputStream fis = null;
try {
fis = new FileInputStream(SAVE_REAL_PATH+"testImage/chen.jpeg");
} catch (FileNotFoundException e) {
}
Bitmap bitmap = BitmapFactory.decodeStream(fis);
return bitmap;
}
3、將Bitmap 轉 爲 byte數組
public static byte[] BitmapBytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
4、採樣壓縮圖片 壓縮比例值越大 壓縮度越高 (size=4 時內存能節約十倍,清晰度差不多)
public Bitmap getScaleBitmap(byte[] data,int size)
{
//1, 得到用來設置圖片的屬性參數對象
BitmapFactory.Options options = new BitmapFactory.Options();
//2, 解碼邊緣
options.inJustDecodeBounds = true;
//3, 進行圖片解碼
BitmapFactory.decodeByteArray(data, 0, data.length, options);
//4, 設置縮放的比例, 只能設置大於1的, 數值越多, 縮放的比例就越小
//壓縮成2的多少次冪 2 -- > 2,3 ; 大於4 小於8 都按4來壓縮
options.inSampleSize = size;
//5, 將圖片的質量設置爲RGB_565
options.inPreferredConfig = Bitmap.Config.RGB_565;
//6,鎖住圖片邊緣
options.inJustDecodeBounds = false;
//7, 通過參數對象, 獲取新的圖片
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
return bitmap;
}
5、保存圖片到本地
//成員變量
private static final String SAVE_PIC_PATH=Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)
? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard/chenxh/mytestApp";//判斷sd卡
private static final String SAVE_REAL_PATH = SAVE_PIC_PATH+ "/res/chenchen";//保存位置
//保存圖片到本地路徑
public static void saveImage(Bitmap bm, String fileName, String path) throws IOException {
String subForder = SAVE_REAL_PATH + path;
File foder = new File(subForder);
if (!foder.exists()) {
foder.mkdirs();
}
File myCaptureFile = new File(subForder, fileName);
if (!myCaptureFile.exists()) {
myCaptureFile.createNewFile();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
}
6、執行
try {
createFolder();
Bitmap bitmap1 = imgToBitmap();
saveImage(getScaleBitmap( BitmapBytes(bitmap1),4),"chen123.jpeg","/testImage");
} catch (IOException e) {
}