Search code examples
javaimagefacebookserver-side

How to generate Image at server side in java [ blob-> string_image -> *.png or .jpg ]


I want to generate an image on server side. My image is stored in a server database in blob format and I am able to convert it into string_image. Then how can I convert that string_image into actual .jpg or .png format?

Actually I am posting attachment as image on users facebook wall. How to generate the image at server side in Java? Is there any sample code to do it?


Solution

  • If you have the image in Blob format then you're best bet it to use ImageIO and read the blob input stream directly.

    This will give you a java.awt.BufferedImage object which you can then render to any type of image using ImageIO. As an OutputStream, you can return that as a body/result from a HTTP GET controller.

    BufferedImage image = ImageIO.read( blob.getInputStream() );
    // Feel free to modify the image here using image.createGraphics()
    // add a water mark if you're feeling adventurous
    byte[] responseBody = toByteArray( image, "png" );
    
    ....    
    protected byte[] toByteArray(BufferedImage image, String type) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, type, baos);
        return baos.toByteArray();
    }
    

    I'm not intimately familiar with how facebook uses images. I think it differs depending on what you're doing. For facebook applications, I think you're still responsible for hosting the image, but facebook will act as a caching proxy and request the image just once, then serve it to all the client that need to see it. If it's a user posted image, then I think facebook stores the image completely (obviously a user uploading a picture does not have it on another server usually).

    If you're looking to just display the image "as is" in response to a a web request, then you can pipe the output of the Blob directly the client, although this keeps database connections open for a while, you might be better copying to a disk cache then serving to the client.

    I have to confess, I couldn't find anything useful about what a stirng_image actually is? Perhaps you could clarify if this answer doesn't meet your needs.