27

i am trying to edit images. but i am getting errors with setPixels.

        picw = pic.getWidth();
        pich = pic.getHeight();
        picsize = picw*pich;        
        int[] pix = new int [picsize];
        pic.getPixels(pix, 0, picw, 0, 0, picw, pich);  
        pic.setPixels(pix,0,pic.getWidth(),0,0,pic.getWidth(),pic.getHeight());

but i am getting illegal state exception with setPixels

Caused by: java.lang.IllegalStateException
  at android.graphics.Bitmap.setPixels(Bitmap.java:878)
  at com.sandyapps.testapp.testapp.onCreate(testapp.java:66)
sandeep
  • 907
  • 2
  • 12
  • 22
  • 1
    possible duplicate of [Android Immutable bitmap crash error](http://stackoverflow.com/questions/13119582/android-immutable-bitmap-crash-error) – S.L. Barth Jan 18 '15 at 20:00

5 Answers5

62

I think your Bitmap is not mutable (see setPixel()'s documentation).

If so, create a mutable copy of this Bitmap (using Bitmap.copy(Bitmap.Config config, boolean isMutable) as an example) and work on this one.

Shlublu
  • 10,693
  • 4
  • 51
  • 69
9

It's simple, just use the following command to change it to a mutable Bitmap:

myBitmap = myBitmap.copy( Bitmap.Config.ARGB_8888 , true);

Now the Bitmap myBitmap is replaced by the same Bitmap but this time is mutable

You can also choose another way of storing Pixels (ARGB_8888 etc..): https://developer.android.com/reference/android/graphics/Bitmap.Config.html

StephenRios
  • 2,083
  • 4
  • 25
  • 41
YOGO
  • 511
  • 3
  • 5
5

Most probably your pic is immutable. By default, any bitmap created from drawable would be immutable.

If you need to modify an existing bitmap, you should do following:

// Create a bitmap of the same size
Bitmap newBmp = Bitmap.createBitmap(pic.getWidth(), pic.getHeight(), Config.ARGB);
// Create a canvas  for new bitmap
Canvas c = new Canvas(newBmp); 

// Draw your old bitmap on it. 
c.drawBitmap(pic, 0, 0, new Paint());
onezeno
  • 744
  • 1
  • 10
  • 21
xandy
  • 27,069
  • 8
  • 58
  • 64
1

I had the same problem. Use to fix it:

BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeResource( getResources(), R.drawable.my_bitmap, opt );
Style-7
  • 659
  • 8
  • 21
0

I was facing this problem and finally fixed after long time.

public static void filterApply(Filter filter){
    Bitmap bitmcopy = PhotoModel.getInstance().getPhotoCopyBitmap();
    //custom scalling is important to apply filter otherwise it will not apply on image
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmcopy, bitmcopy.getWidth()-1, bitmcopy.getHeight()-1, false);
    filter.processFilter(scaledBitmap);
    filterImage.setImageBitmap(scaledBitmap);
}
Laeeq Khan Niazi
  • 337
  • 2
  • 10