Android处理图像数据转换的各种方法
android中处理图像是一件很常见的事情,这里记录备忘一些亲身使用过的处理图片数据的方法。
转为bitmap
rgb值转bitmap
private bitmap createcolorbitmap(string rgb, int width, int height) {
bitmap bmp = bitmap.createbitmap(width, height, bitmap.config.argb_8888);
int color = color.parsecolor(rgb);
bmp.erasecolor(color);
return bmp;
}
//usage
bitmap bmp = createcolorbitmap("#cce8cf", 200, 50);
color值转bitmap
private bitmap createcolorbitmap(int color, int width, int height) {
bitmap bmp = bitmap.createbitmap(width, height, bitmap.config.argb_8888);
bmp.erasecolor(color);
return bmp;
}
//usage
bitmap bmp = createcolorbitmap(color.blue, 200, 50);
字节数组转bitmap
private bitmap getbitmapfrombytearray(byte[] array) {
return bitmapfactory.decodebytearray(array, 0, array.length);
}
读取文件转bitmap
private bitmap getbitmapfromfile(string pathname) {
return bitmapfactory.decodefile(pathname);
}
读取资源转bitmap
private bitmap getbitmapfromresource(resources res, int resid) {
return bitmapfactory.decoderesource(res, resid);
}
输入流转bitmap
private bitmap getbitmapfromstream(inputstream inputstream) {
return bitmapfactory.decodestream(inputstream);
}
drawable转bitmap
bitmap icon = bitmapfactory.decoderesource(context.getresources(),r.drawable.icon_resource);
转为drawable
资源转drawable
drawable drawable = getresources().getdrawable(r.drawable.ic_launcher);
bitmap转drawable
drawable d = new bitmapdrawable(getresources(),bitmap);
图片圆角展示
通过对图片数据bitmap进行处理即可,其中pixels为边角的半径。
public static bitmap getroundedcornerbitmap(bitmap bitmap, int pixels) {
bitmap output = bitmap.createbitmap(bitmap.getwidth(), bitmap
.getheight(), config.argb_8888);
canvas canvas = new canvas(output);
final int color = 0xff424242;
final paint paint = new paint();
final rect rect = new rect(0, 0, bitmap.getwidth(), bitmap.getheight());
final rectf rectf = new rectf(rect);
final float roundpx = pixels;
paint.setantialias(true);
canvas.drawargb(0, 0, 0, 0);
paint.setcolor(color);
canvas.drawroundrect(rectf, roundpx, roundpx, paint);
paint.setxfermode(new porterduffxfermode(mode.src_in));
canvas.drawbitmap(bitmap, rect, rect, paint);
return output;
}