Android 图片加载经常出现内存OOM异常,处理起来也很复杂,主要是图片分辨率过大(如:2880*1620),但是基本原理大概如下:
public static Bitmap oomSolution(Resources res,int resID,int widthpx,int heightpx){
Options options =new BitmapFactory.Options();
options.inJustDecodeBounds=true;//不在内存中读取图片
options.inPreferredConfig = Bitmap.Config.RGB_565;//代表RGB位图
BitmapFactory.decodeResource(res,resID, options);//压缩前图片
int width= options.outWidth;//原始图片宽
int height=options.outHeight;//原始图片高
if(height>heightpx||width>widthpx){
int inheight=Math.round((float)height/(float)heightpx);
int inwidth=Math.round((float)width/(float)widthpx);
int inSize=inheight>inwidth?inheight:inwidth;
options.inSampleSize=inSize;//缩放值:1不缩放 2为缩放1/2
}
options.inJustDecodeBounds=false;//在内存中创建图片
Bitmap bm = BitmapFactory.decodeResource(res,resID, options);//压缩后的图片
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,20, baos);//压缩图片
return bm;
}
来源:http://blog.csdn.net/a704755096/article/details/49912211
附:Bitmap图片转换工具
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Matrix;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
public class BitmapUtils {
/**
*Bitmap to Drawable
* @param bmp
* @return Drawable
*/
public static Drawable getBitmapDrawable(Bitmap bmp) {
BitmapDrawable bd = new BitmapDrawable(bmp);
return bd;
}
/**
* Drawable to Bitmap
* @param drawable
* @return Bitmap
*/
public static Bitmap getDrawableBitmap(Drawable drawable) {
BitmapDrawable bd = (BitmapDrawable) drawable;
Bitmap bm = bd.getBitmap();
return bm;
}
/**资源图片Resources to Bitmap
* @param activity
* @param resId
* @return Bitmap
*/
public static Bitmap getResourcesBitmap(Activity activity, int resId) {
Resources res = activity.getResources();
return BitmapFactory.decodeResource(res, resId);
}
/**数组转图片byte[] to Bitmap
* @param bytee
* @return Bitmap
*/
public static Bitmap getBytesBimap(byte[] bytee) {
if (bytee.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(bytee, 0,bytee.length);
}
/**图片转数组Bitmap to byte[]
* @param bm
* @return byte[]
*/
public static byte[] getBitmapBytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,20, baos);
return baos.toByteArray();
}
/**放大图片
* @param bitmap
* @return Bitmap
*/
public static Bitmap getBigBitmap(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.postScale(1.5f,1.5f); //长和宽放大缩小的比例
Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
return resizeBmp;
}
/**缩小图片
* @param bitmap
* @return Bitmap
*/
public static Bitmap getSmallBitmap(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.postScale(0.4f ,0.4f); //长和宽放大缩小的比例
Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
return resizeBmp;
}
/**圆形图片
* @param source
* @return Bitmap
*/
public static Bitmap getCircleImage(Bitmap source) {
int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source,Shader.TileMode.CLAMP,Shader.TileMode.CLAMP));//遮罩
Bitmap bmp = Bitmap.createBitmap(length,length,source.getConfig());
Canvas canvas = new Canvas(bmp);
canvas.drawCircle(length / 2, length / 2, length / 2, paint);
return bmp;
}
/**线程获取url图片url to Bitmap
* @param img imageview textview…
* @param urlstr url地址
* @param isCircular true圆形,false不变
*/
public static void getUrlBitmap(final View img,final String urlstr,final boolean isCircular){
if(urlstr==null||urlstr.trim().length()==0){
return;
}
new Thread(){
@Override
public void run() {
super.run();
try {
URL url = new URL(urlstr);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
final Bitmap map = BitmapFactory.decodeStream(in);
final Drawable bdrawable=getBitmapDrawable(isCircular?getCircleImage(map):map);
in.close();
img.post(new Runnable() {
@Override
public void run() {
img.setBackgroundDrawable(bdrawable);
}
});
} catch (Exception e) {
// e.printStackTrace();
}
}
}.start();
}
/**截屏Screenshot(view转Bitmap)加背景框http://blog.csdn.net/yanzi1225627/article/details/8622257
* @param view 当前视图截屏getWindow().getDecorView()
* @return Bitmap
*/
public static Bitmap getScreenshotBitmap(View view){
//当前视图截屏view=getWindow().getDecorView()
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
Bitmap bitmap=null;
if (viewWidth > 0 && viewHeight > 0) {
bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Config.RGB_565);
Canvas cvs = new Canvas(bitmap);
//cvs.drawColor(view.getDrawingCacheBackgroundColor());
view.draw(cvs);
// MediaStore.Images.Media.insertImage(getContentResolver(),bitmap,"title","description");//保存下载到相册-返回uriString
// sendBroadcast(new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(new File(uri2path(this,uriString)))));//刷新相册-PhotoUtils.uri2path
return bitmap;
}
// MediaMetadataRetriever retriever = new MediaMetadataRetriever();//本地视频截图
// retriever.setDataSource(filePath);
// String timeString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
// retriever.getFrameAtTime(Long.parseLong(timeString) * 1000);
return bitmap;
}
/**复制文件图片OOM(file to Bitmap)
* @param filepath 大文件/图片原地址
* @param newpath 压缩复制后的新地址
* @return Bitmap
*/
public static Bitmap getOOMBitmap(String filepath,String newpath){
File oldfile = new File(filepath=filepath==null?"":filepath);
long length = (oldfile==null?0:oldfile.length());//b
File file = new File(newpath);
if ( !file.exists() ) {
file.getParentFile().mkdirs();
}
Options options =new BitmapFactory.Options();
options.inJustDecodeBounds=true;//不在内存中读取图片
options.inPreferredConfig = Bitmap.Config.RGB_565;//代表RGB位图
options.inSampleSize=1;//缩放值:1不缩放 2为缩放1/2
BitmapFactory.decodeFile(filepath, options);//压缩前图片
options.inJustDecodeBounds=false;//在内存中创建图片
Bitmap bm = BitmapFactory.decodeFile(filepath, options);//压缩后的图片
try {
FileOutputStream fos = new FileOutputStream(newpath);
int per=length<1024*1000?80:(length<1024*2000?50:40);
bm.compress(Bitmap.CompressFormat.JPEG, per, fos);//压缩图片
fos.close();
}catch (Exception e){
// e.printStackTrace();
}
return bm;
}
}