如何设置在J2ME(Java)的图像高度和宽度
问题描述:
我创建从图像URL的图像(LCDUI图像)如何设置在J2ME(Java)的图像高度和宽度
HttpConnection c = (HttpConnection) Connector.open(imageurl);
int len = (int)c.getLength();
if (len > 0)
{
is = c.openDataInputStream();
byte[] data = new byte[len];
is.readFully(data);
img = Image.createImage(data, 0, len);
我想高度和宽度设置为这个?我想显示
答
您无法设置宽度和高度到图像。但是,您可以使用下面的方法调整图片的大小。
public Image resizeImage(Image src, int screenHeight, int screenWidth) {
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
Image tmp = Image.createImage(screenWidth, srcHeight);
Graphics g = tmp.getGraphics();
int ratio = (srcWidth << 16)/screenWidth;
int pos = ratio/2;
//Horizontal Resize
for (int index = 0; index < screenWidth; index++) {
g.setClip(index, 0, 1, srcHeight);
g.drawImage(src, index - (pos >> 16), 0);
pos += ratio;
}
Image resizedImage = Image.createImage(screenWidth, screenHeight);
g = resizedImage.getGraphics();
ratio = (srcHeight << 16)/screenHeight;
pos = ratio/2;
//Vertical resize
for (int index = 0; index < screenHeight; index++) {
g.setClip(0, index, screenWidth, 1);
g.drawImage(tmp, 0, index - (pos >> 16));
pos += ratio;
}
return resizedImage;
}
答
您不需要设置宽度和高度,因为在图像加载过程中会加载并设置此信息。所以,如果图像是320x100,您的代码将创建一个320x100的图像。 img.getWidth()
将返回320 img.getHeight()
将返回100
这是不能够改变的Image
对象的宽度和高度。你可以查询它的宽度和高度。
您的图像已准备好在画布中呈现在ImageItem
对象中。
答
接受的答案并没有为我工作(因为它沿着减小图像大小时图像的左下方一条白色带 - 尽管保持相同的宽高比)。我找到了一个从CodeRanch forum工作的代码片段。
下面是片段中,清理:
protected static Image resizeImage(Image image, int resizedWidth, int resizedHeight) {
int width = image.getWidth();
int height = image.getHeight();
int[] in = new int[width];
int[] out = new int[resizedWidth * resizedHeight];
int dy, dx;
for (int y = 0; y < resizedHeight; y++) {
dy = y * height/resizedHeight;
image.getRGB(in, 0, width, 0, dy, width, 1);
for (int x = 0; x < resizedWidth; x++) {
dx = x * width/resizedWidth;
out[(resizedWidth * y) + x] = in[dx];
}
}
return Image.createRGBImage(out, resizedWidth, resizedHeight, true);
}
上面的代码(其不编译)可能已经从例如采取此页面上 - http://www.oracle.com/technetwork/ java/image-resizing-137933.html - 它会编译,但在我的测试中,不会正确调整图像大小,因为它会在图像底部留下白色条带。 – 2015-02-20 14:11:02