29 Aralık 2010 Çarşamba

How to construct image from byte array for gwt applications

Here is the scenario. You have images stored in database, and you want to use these images in your gwt application. As already known, the gwt image object constructor takes only String , this string should represent the url of the image.. You can  construct the image in the server, and you can save this image to your server's disk, and you can use the url of this image . But , this solution is not elegant, you have to save image to the server's disk..

As a second solution, you can write a servlet whose purpose is to fetch images from database and send them to the clients..  You can map this servlet ImageViewer , with  a  parameter. The request looks like this ;
   /imageViewer?imageId=1234 . You should create your gwt image widget like below;


  Image image = new Image( "/imageViewer?imageId=1234");



 ImageViewer servlet doGet method should be like that ;


public void doGet(HttpServletRequest request, HttpServletResponse response) {
        String imageId =  request.getParameter("imageId");
         byte[] imageData = readImageDataFromDB(imageId);
         response.setContentType("image/png");
         response.getOutputStream().write(imageData,0,imageData.length);
}




As a third solution , you can use the below code to convert image byte array data, to Base64 encoded string.. But you should know that this method does not work for IE7 and the previous versions. IE8 has 32 kb limit for encoded data.


public String getImageData(){

   byte[] imageByteArray = readImageDataFromDB(); //
   String base64 = com.google.gwt.user.server.Base64Utils.toBase64(imageByteArray);
    base64
= "data:image/png;base64,"+base64; 
   return base64;
}

And at gwt layer, you should use the below code ;


 
imageService.getImageData(new AsyncCallback() {
    @Override  
     public void onSuccess(String imageData) {    
       
Image image = new Image(imageData);    
        
RootPanel.get("image").add(image);  

      }
     @Override 
     public void onFailure(Throwable caught) {
      
Window.alert(caught.getMessage()); 

     }
}

2 yorum:

  1. excellent solution thnks for article.

    YanıtlaSil
  2. Hello Sir,
    I followed as the same whatever you said, but in the client side i got a huge string starts with "data:image/png;base64,WXCixgeWxmx....like that. but in the image I could not get (no any error shows on console)

    my project part of the step is:
    I have a class named "MapClient" extends com.smartgwt.client.widgets.Window, this class has a inner class, that class extends com.smartgwt.client.widgets.Canvas your client part getImageData() is here. and I add the image into this.addChild(image);
    then the Canvas class add into mapClient.addMember(Canvas Class) please clear my problem, What I have done mistake and what I have to do??
    Thanks in Advance
    Ramanan

    YanıtlaSil