Search code examples
javaandroidpixel

How to fix IlegalStateException on Android when I try to change a pixel color


I was trying to use the following code to change a White pixel to a Transparent pixel.

private void transformPixelWhiteToTransparent() {
    MyLog.i(this, "removePixelBrancoDeImagem iniciado");

    String nomeArquivo = "RESMARFOC0001.jpg";
    File file = new File( "sdcard/Imagem/"+nomeArquivo);
    String path = file.getAbsolutePath();
    MyLog.i(this, "path: "+path);
    if(file.exists()) {  
        try{
            MyLog.i(this, "file exists");
            Bitmap bm = BitmapFactory.decodeFile(path);
            MyLog.i(this, "cheguei fim");

            for(int x = 0; x<bm.getWidth(); x++){
                for(int y = 0; y<bm.getHeight(); y++){
                    if(bm.getPixel(x, y) == Color.WHITE){
                        bm.setPixel(x, y, Color.TRANSPARENT);
                    }
                }
            }

            MyLog.i(this, "fim salvar arquivo");
        }catch (Exception e){
            MyLog.i(this, "erro: "+e);
        }

    }
}

But I get the error IlegalStateException in the following line

"bm.setPixel(x, y, Color.TRANSPARENT);"

How can I fix that?


Solution

  • I found a way to make my code work.

    private void transformPixelWhiteToTransparent() {
        String nomeArquivo = "RESMARFOC0001.jpg"; // crie uma marca e depois troque o nome dela aqui
        File file = new File( "sdcard/Imagem/"+nomeArquivo);
        String path = file.getAbsolutePath();
        if(file.exists()) {  // se arquivo existe carrega para upload
    
            try{
                Bitmap bm1 = BitmapFactory.decodeFile(path);
                bm1.setHasAlpha(true);
                Bitmap bmMod = bm1.copy(bm1.getConfig(),true);
    
                for(int x = 0; x<bmMod.getWidth(); x++){
                    for(int y = 0; y<bmMod.getHeight(); y++){
                        if(bmMod.getPixel(x, y) == Color.WHITE){
                            bmMod.setPixel(x, y, Color.TRANSPARENT); // Color.BLUE
                        }
                    }
                }
                // more code to save the bitmap as PNG file
    
            }catch (Exception e){
                MyLog.i(this, "erro: "+e);
            }
    
        }
    }
    

    The only difference from my previous code is that line

    Bitmap bmMod = bm1.copy(bm1.getConfig(),true);
    

    I need to create a copy of the original Bitmap to be able to modify the copied Bitmap.