I'm doing an algorithm that converts a bitmap leaving it in shades of gray.
I was able to do it using for but I would like to do it recursively.
Using for (This is working fine)
//BUTTON - ON CLICK . . .
public void go(View v){
//BM_3 É UM BITMAP, VARIAVEL GLOBAL QUE JÁ POSSUI UMA IMAGEM EM SEU CONTEUDO . . .
bm_3 = bm_3.copy(Bitmap.Config.ARGB_8888, true);
for (int x = 0; x < bm_3.getWidth(); x++){
for (int y = 0; y < bm_3.getHeight(); y++) {
String hex = Integer.toHexString(bm_3.getPixel(x, y));
if(hex.length() == 8) {
String hexX = "#" + convert_Hex_to_grey("" + hex.charAt(0) + hex.charAt(1),
"" + hex.charAt(2) + hex.charAt(3),
"" + hex.charAt(4) + hex.charAt(5),
"" + hex.charAt(6) + hex.charAt(7));
bm_3.setPixel(x, y, Color.parseColor(hexX));
}
}
}
//IMG É UMA IMAGEVIEW . . .
img.setImageBitmap(bm_3);
}
Based on the algorithm above, I tried to implement it recursively. However, it has an error of java.lang.StackOverflowError: stack size 1038KB
Using recursion (java.lang.StackOverflowError)
RESOURCES
private Bitmap grey_scale(int x, int y, Bitmap bm_3) {
//IF PARA PERCORRER TODO Y . . .
if (y < bm_3.getHeight()) {
String hex = Integer.toHexString(bm_3.getPixel(x, y));
if (hex.length() == 8) {
String hexX = "#" + convert_Hex_to_grey("" + hex.charAt(0) + hex.charAt(1),
"" + hex.charAt(2) + hex.charAt(3),
"" + hex.charAt(4) + hex.charAt(5),
"" + hex.charAt(6) + hex.charAt(7));
bm_3.setPixel(x, y, Color.parseColor(hexX));
}
//O ERRO OCORRE NESTE RETURN ! ! !
return grey_scale(x, y+1, bm_3);
}
//IF PARA PERCORRER TODO X, ZERANDO Y A CADA TROCA DE X.
if (x < bm_3.getWidth()) {
return grey_scale(x+1, 0, bm_3);
}
//RETORNA BITMAP
return bm_3;
}
BUTTON ON CLICK THAT CALLS FOR RESOURCE
public void go(View v){
bm_3 = bm_3.copy(Bitmap.Config.ARGB_8888, true);
//FAZ RECURSAO DENTRO DE UMA THREAD . . .
new Thread(new Runnable() {
@Override
public void run() {
//CHAMA A RECURSAO
bm_3 = grey_scale(0, 0, bm_3);
//VOLTA PRA THREAD PRINCIPAL PARA ATUALIZAR O IMAGEVIEW . . .
runOnUiThread(new Runnable() {
@Override
public void run() {
img.setImageBitmap(bm_3);
}
});
}
}).start();
}