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) {
}