这段 Android 的 Java 代码有什么问题?
我编写了这段代码来将图像分成 9 个部分,但它给了我运行时错误。 LogCat 没有错误,我被卡住了。错误出现在从底部开始的第 7 行 (Bitmap.createBitmap(...);)。
public Bitmap[] getPieces(Bitmap bmp) {
Bitmap[] bmps = new Bitmap[9];
int width = bmp.getWidth();
int height = bmp.getHeight();
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;
}
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.getHeight();
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是 android 框架的一个限制,它不会给出正确的错误消息。理想的解决方案是将代码包装在 try / catch 块中,并将异常记录到控制台并相应地修复代码,但仅将其用于调试目的。
上面的代码从这里提取:
http://moazzam-khan.com/blog/?p= 41
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.
The above code extracted from here:
http://moazzam-khan.com/blog/?p=41
而不是
用来
避免获取(至少部分)不存在的图像部分。
Instead of
use
to avoid fetching parts of the image that (at least partly) don't exist.
在您的代码中,piece 可以大于 8,因此您的 bmp 索引超出了范围。您需要重写它,以便最右边和最底部的部分只具有所有额外的部分,并且大小不一定相同。
或者,如果您需要它们具有相同的大小,请删除多余的行/列。为了确保这一点,我会像这样制定我的 for 循环
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