开发者

What's wrong with this Java code for Android?

I have written this piece of code to break an image into 9 pieces and it gives me runtime error. There is no error in LogCat and I am stuck. The error comes at line 7 line from bottom (Bitmap.createBitmap(...);).

public Bitmap[] getPieces(Bitmap bmp) {
        Bitmap[] bmps = new Bitmap[9];

        int width = bmp.getWidth();
        int height = bmp.getH开发者_JAVA技巧eight();

        int rows = 3;
        int cols = 3;

        int cellHeight = height / rows;
        int cellWidth = width / cols;

        int piece = 0;

        for (int x = 0; x <= width; x += cellWidth) {
            for (int y = 0; y <= height; y += cellHeight) {
                Bitmap b = Bitmap.createBitmap(bmp, x, y, cellWidth,
                        cellHeight, null, false);
                bmps[piece] = b;
                piece++;
            }
        }

        return bmps;
    }


It is a limitation of android framework which doesn't give proper error message. The ideal solution would be to wrap your code in try / catch block and log the exception to console and fix your code accordingly, but use it only for debugging purposes.

try {
    // Code
}
catch (Exception e) {
    Log.e("ERROR", "ERROR IN CODE:"+e.toString());
}

The above code extracted from here:

http://moazzam-khan.com/blog/?p=41


Instead of

    for (int x = 0; x <= width; x += cellWidth) {
        for (int y = 0; y <= height; y += cellHeight) {

use

    for (int x = 0; x+cellWidth < width; x += cellWidth) {
        for (int y = 0; y+cellHeight < height; y += cellHeight) {

to avoid fetching parts of the image that (at least partly) don't exist.


In your code, piece can be greater than 8, so you are getting index out of bounds on bmps. You need to rewrite it so that the right-most and bottom-most pieces just have all of the extra and aren't necessarily the same size.

Or, if you need them to be the same size, drop the extra rows/cols. To make sure, I would formulate my for loop like this

   for (int cellX = 0; cellX < 3; cellX++) {
        int x = cellX * cellWidth;
        for (int cellY = 0; cellY < 3; cellY++) {
               int y = cellY * cellHeight;
               // find the cellWidth/Height that doesn't overflow the original image
               Bitmap b = // get the bitmap

               bmps[piece] = b;
               piece++;
        }
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜