开发者

How can I convert an Image to byte array in J2ME?

My requirement is like this. I need to read a file from the Mobile phone using a file connection, create a thumbnail of that image and post to the server. I am able to read the image using the FileConnection API, and also able to create the thumbnail.

After creating the thumbnail, I am not able find a method to convert back that image to byte[]. Is开发者_JAVA技巧 it possible?

Code for thumbnail conversion:

    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;
    }


MIDP2.0's Image.getRGB() is your friend. You can obtain the ARGB pixel data as an int array as follows:

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

The int array can then be used as a parameter to Image.createRGBImage(), or in desktop Java, BufferedImage can be used as follows:

BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
img.setRGB(0, 0, w, h, ints, 0, w);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜