views:

40

answers:

3

hi,

i have a requirement, i want to take URL of image from user and then convert it to bytes format, and send it my server, i am using tomcat as web-app server and hibernate as ORM tool, i am already written the server side code for saving the incoming bytes into a table using BLOB, but my problem is that how can i convert the image into array of bytes, so that i can send the array to server to process further.

And adding to above, i can load the data, from table, and then can send the bytes back to client, but how to convert the bytes back to image.

Currently, i am using HTML at client side for web pages and Servlets for request and response.

Please help me.

A: 

Check the ImageIO class in java. It has methods for both reading and writing images. For more information check here.

Faisal Feroz
A: 

It seems that you dont need to do any special computation on your images. Just store them and send them back to a browser. If this is the case, you dont actually need to treat them as images, you can just handle them as java.io.File. Then you can store them as BLOB in your database.

To help you manage the upload you can use commons-fileupload. Or if you are using SpringMVC, have a look at the Multipart Resolver.

Guillaume
+1  A: 

If it's an image URL, then just read the URL straight into a byte array, like this:

public static byte[] getBytesFromURL(URL url) throws IOException {
    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
        in = url.openStream();
        out = new ByteArrayOutputStream();
        int len;
        byte[] buf = new byte[1024 * 4];
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len);
        }
        byte[] bytes = out.toByteArray();
        return bytes;

    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}
dogbane