本地有一张比较大分辨率的图片(4480*3600) 现在想将它转换成宽为2048的 高度等比缩小。然后保存至本地的另一个文件内(处理过后的文件大小不能原来的大)。现在苦恼的怎么压缩这是很头疼的问题,直接通过bitmap获取的话,就会出现oom错误。通过java的一套处理图片机制,但是里面的一些类没有办法适用(比如Image,新建一个java工程是可以使用的,但是在android工程里是用不了,最后这种方法也不了了之)。请大家伙帮帮提供一下思路。
为这个问题已经纠结了两天了
解决方案 »
- 最近想做一个像facebook的侧边栏,但是刷新页面的功能无法实现
- httpCliet与httpURLConnection 主要区别及使用场合
- 运行不了SDK Manager.exe
- 关于addView的问题
- ? - SharedPreferences无法commit
- 请问Android下如何同时使用GPRS和Wifi
- 手机通话界面最小化
- 用 ndk 编译,在 jni 中调用 parcel
- 求助错在哪里?报错java.lang.ArrayIndexOutOfBoundsException:length=1;index=1
- scrollview和horizontalscrollview和relativelayout混合使用
- 请问怎么设置全局的onTouchEvent事件呢?
- 使用谷歌自带api无法准确定位问题
楼主可以参考下
// 图片源
// Bitmap bm = BitmapFactory.decodeStream(getResources()
// .openRawResource(id));
// 获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
// 设置想要的大小
int newWidth1 = newWidth;
int newHeight1 = newHeight;
// 计算缩放比例
float scaleWidth = ((float) newWidth1) / width;
float scaleHeight = ((float) newHeight1) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
true);
return newbm; }
第一步用inSampleSize 压缩一部分倍数,使内存无溢出
第二步用Matrix精确调整
private Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 开始读入图片, 此时把options.inJustDecodeBounds 设回true了
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 = 200f;// 这里设置高度为800f
float ww = 120f;// 这里设置宽度为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;// 设置缩放比例
System.out.println(newOpts.inSampleSize);
// 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return bitmap;// 压缩好比例大小后再进行质量压缩
}