(1)图片占用内存的计算方式:
一张522*686的PNG 图片,我把它放到 drawable-xxhdpi 目录下,在三星s6上加载,占用内存2547360B,其中 density 对应 xxhdpi 为480,targetDensity 对应三星s6的密度为640:
522/480 * 640 * 686/480 *640 * 4 = 2546432B
(2)设置图片的图片模式:下面设置为每个像素占两个字节,为无透明的模式。
BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565; a.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.a,options));
(3)改变Bitmap的大小
Bitmap.createScaledBitmap(Bitmap,width,height,true);
(4)改变Bitmap 的颜色属性:
Bitmap b = response.copy(Bitmap.Config.RGB_565,false);
response是Bitmap对象,注意此方法会重新创建一个新的Bitmap对象,如果前者不需要了,要做好清空操作。
(5)压缩图片:
package com.example.administrator.myapplication;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
Bitmap bitMap;
static String str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
mImageView = (ImageView) findViewById(R.id.imageView2);
try {
bitMap = decodeSampledBitmapFromResource(getResources(), R.drawable.android1, 200, 310);
} catch (Exception e) {
}
mImageView.setImageBitmap(bitMap);
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int MyWidth, int MyHeight) throws Exception {
final BitmapFactory.Options options = new BitmapFactory.Options();
/**被赋值为true返回的Bitmap为null,虽然Bitmap是null了,但是BitmapFactory.Options的outWidth、
*outHeight和outMimeType属性都会被赋值。这个技巧让我们可以在加载图片之前就获取到图片的长宽值和MIME类型,从而根据情况对图片进行压缩
*/
options.inJustDecodeBounds = true;
str = options.outMimeType;
BitmapFactory.decodeResource(res, resId, options);
//得到压缩倍数。
options.inSampleSize = calculateInSampleSize(options, MyWidth, MyHeight);
//设置为false,就能得到Bitmap.
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) throws Exception {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}
return inSampleSize;
}
}