views:

825

answers:

1

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 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;
    }
+1  A: 

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);
funkybro
for uploading image to the server,i need to convert this argb int array to byte array.i can do this with this code ByteArrayOutputStream baos = new ByteArrayOutputStream();DataOutputStream dos = new DataOutputStream( baos );for( int i = 0; i < argb.length; i++ ) { dos.writeInt( argb[i] ); }byte[] imageData = baos.toByteArray();but the problem is that its creating encoding problems in the server.I use Base64 encoder and decode it back in the server.i am getting the desired result if i use the original image.but the thumbnail image is having the problem.
Sanal
If you:deserialize the byte array correctly, rebuild the int array, transmit the width and height of the image to the server, and then attempt to create the image as suggested, you should then be able to save the image in whatever format you like.
funkybro