Android 更改位图中的像素
我想动态更改位图的像素,但它是不可变的,因此它返回一个非法状态异常 这是我的代码:Android 更改位图中的像素,android,bitmap,pixel,Android,Bitmap,Pixel,我想动态更改位图的像素,但它是不可变的,因此它返回一个非法状态异常 这是我的代码: Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image); int[] pixels = new int[bm.getWidth()*bm.getHeight()]; bm.getPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
int[] pixels = new int[bm.getWidth()*bm.getHeight()];
bm.getPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());
//…处理像素
bm.setPixels(pixels, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());
例如,要将位图的前四行变为蓝色:
import android.graphics.Color;
int[] pixels = new int[myBitmap.getHeight()*myBitmap.getWidth()];
myBitmap.getPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
for (int i=0; i<myBitmap.getWidth()*4; i++)
pixels[i] = Color.BLUE;
myBitmap.setPixels(pixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
使用下面的方法从资源中获取可变位图
public static Bitmap getMutableBitmap(Resources resources,int resId) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
return BitmapFactory.decodeResource(resources, resId, options);
}
或使用
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
从不变位图获取可变位图。可能的重复是否可以更改位图像素的大小?
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);