如何在J2ME中将图像转换为字节数组?

时间:2009-12-08 13:35:35

标签: image java-me bytearray midp lcdui

我的要求是这样的。我需要使用文件连接从手机中读取文件,创建该图像的缩略图并发布到服务器。我能够使用FileConnection API读取图像,并且还能够创建缩略图。

创建缩略图后,我找不到将该图像转换回byte []的方法。有可能吗?

缩略图转换代码:

    private Image createThumbnail(Image image) {
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();

        int thumbWidth = 128;
        int thumbHeight = -1;

        if (thumbHeight == -1)
            thumbHeight = thumbWidth * sourceHeight / sourceWidth;

        Image thumb = Image.createImage(thumbWidth, thumbHeight);
        thumb.getGraphics();
        Graphics g = thumb.getGraphics();

        for (int y = 0; y < thumbHeight; y++) {
            for (int x = 0; x < thumbWidth; x++) {
                g.setClip(x, y, 1, 1);
                int dx = x * sourceWidth / thumbWidth;
                int dy = y * sourceHeight / thumbHeight;
                g.drawImage(image, x - dx, y - dy);
            }
        }

        Image immutableThumb = Image.createImage(thumb);

        return thumb;
    }

1 个答案:

答案 0 :(得分:2)

MIDP2.0的Image.getRGB()是你的朋友。您可以将ARGB像素数据作为int数组获取,如下所示:

int w = theImage.getWidth();
int h = theImage.getHeight();
int[] argb = new int[w * h];
theImage.getRGB(argb, 0, w, 0, 0, w, h);

然后可以将int数组用作Image.createRGBImage()的参数,或者在桌面Java中,BufferedImage可以按如下方式使用:

BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
img.setRGB(0, 0, w, h, ints, 0, w);
相关问题