一、创建bitmap对象
Bitmap是一个final类,因此不能被继承。Bitmap只有一个构造方法,且该构造方法是没有任何访问权限修饰符修饰,官方解释为private的
所以Bitmap不能直接new。但是我们可以利用Bitmap的静态方法createBitmap()和BitmapFactory的decode系列静态方法创建Bitmap对象。
ps:Bitmap.createBitmap()与其说是创建Bitmap对象,个人感觉不如说是对bitmap对象进行操作然后得到的新的Bitmap对象
1)createBitmap(Bitmap source, int x, int y, int width, int height):从原位图中指定坐标点(x,y)开始,从中挖取宽width、高height的一块出来,创建新的Bitmap对象。
2)createScaledBitmap(Bitmap source, int dstWidth, int dstHeight, boolean filter):对源位图进行缩放,缩放成指定width、height大小的新位图对象。
3)createBitmap(int width, int height, Bitmap.Config config):创建一个宽width、高height的新位图。
4)createBitmap(Bitmap source, int x, int y, int width, int height, Matrix matrix, boolean filter):从原位图中指定坐标点(x,y)开始,
从中挖取宽width、高height的一块出来,创建新的Bitmap对象。并按Matrix指定的规则进行变换。
Matrix matrix = new Matrix();
matrix.postScale(0.8f,0.8f); // 缩放0.8
matrix.postRotate(-45); // 逆时针旋转45°
matrix.postTransLate(100,80);// 旋转中心为(100,80)
BitmapFactory是一个工具类,它提供了大量的方法来用于从不同的数据源来解析、创建Bitmap对象
1)decodeFile(String pathName):从pathName指定的文件中解析、创建Bitmap对象。
2)decodeFileDescriptor(FileDescriptor fd):从FileDescriptor对应的文件中解析、创建Bitmap对象。
3)decodeResource(Resources res, int id):根据给定的资源ID从指定资源中解析、创建Bitmap对象。
4)decodeStream(InputStream is):从指定的输入流中解析、创建Bitmap对象
5)decodeByteArray(byte[] data, int offset, int length):从指定的字节数组的offset位置开始,将长度为length的字节数据解析成Bitmap对象。
简易例子:
URL conurl = new URL(url);
HttpURLConnection con = (HttpURLConnection) conurl.openConnection();
bmp = BitmapFactory.decodeStream(con.getInputStream());
其他
1、
Resources resources = mContext.getResources();
Drawable drawable = resources.getDrawable(R.drawable.a);
imageview.setBackground(drawable);
2、
Resources r = this.getContext().getResources();
Inputstream is = r.openRawResource(R.drawable.my_background_image);
BitmapDrawable bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();
3、
Bitmap bmp=BitmapFactory.decodeResource(r, R.drawable.icon);
Bitmap newb = Bitmap.createBitmap( 300, 300, Config.ARGB_8888 );
4、
InputStream is = getResources().openRawResource(R.drawable.icon);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
二、简易优化
谷歌推荐压缩方式
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}