Image Scaling using servlet

Hi guys ,
I am facing problems where i have to download a image from a database and scale it to a thumbnail.
i am using below code to get the image from db and to write it to stream.
  conn = Utilities.getDBConnection();
           stream = response.getOutputStream();
           ps = conn.prepareStatement("query");
           rs = ps.executeQuery();
           while(rs.next())
               Blob attach = null;
               byte[] blobBytesArray = null;
               attach = rs.getBlob(1);
               int len = new Integer( new Long( attach.length()).toString() ).intValue();
               blobBytesArray = attach.getBytes(1,len);
               if (blobBytesArray != null)
                 if (blobBytesArray.length > 0 )
                      stream.write(blobBytesArray) ;
                      stream.flush();
                      stream.close();
              }How to scale this image?

Apparently you want to display this image in a webpage, so I'd say that CSS is the way to scale the displayed image.
If you want to do it in the servlet you'd have to turn the image into a BufferedImage (using the ImageIO class) and use the Graphics class to create a scaled instance of it, then output the binary image data of the scaled instance back to the servlet's outputstream using the ImageIO class again.

Similar Messages

  • Sending thumbnail of images to client on request using servlet/jsp

    hi
    can anybody tell me how can we send thumbnail of more than one image to client using servlet or jsp just the way we thumbnail of images in google

    Then create a servlet which uses Java 2D API to rezise the image and writes it to the outputstream of the response. Call that servlet in the <img> tag along with an unique request parameter identifying the image.

  • How to save image using an image object in servlet on web server

    I'll be very thankful to anyone who helps me in this matter.
    i developed an applet which draws on a buffered image.
    now i want to save this buffered image as a jpg image on the web server.
    i know i have to use servlets or jsp for this.
    but i want to use servlet for specific reasons.
    can anyone plz provide me the code for taking an image object from an applet and saving it thru servlet.
    i need this solution as soon as possible.
    thanks in advance.

    Take a look around for URLConnection, and Applet to Servlet communication (also check the [url http://forum.java.sun.com/forum.jsp?forum=33]Servlet forum).
    Basic concepts will be to open a URLConnection to the URL mapped on your server for the servlet, then send the image, byte by byte, to the servlet, then ask for a reply from the servlet.
    Once asked for a reply the servlet will need to take the image sent to it (hopefully via an HTTP post) and copy it to a location on disk. (You could have a parameter to the request that tells you want to name the file...)
    As for the converting buffered image to JPEG, I haven't done this before, but I know others have. You can look around (more likely to find it in the [url http://forum.java.sun.com/forum.jsp?forum=31]Java Programing[ul] forum) for the code needed.

  • Downloading image using servlet/jsp

    Has anyone tried downloading a .gif image using servlet/jsp ??!?

    Yes, there's even an example in my book about servlets.

  • Acrobat X problem with image scaling in Excel

    We are using Acrobat X standard with Excel 2007.
    The problem is that when using the Create PDF button on the Acrobat toolbar within Excel, if the document has been scaled using Page Layout-Scale option within Excel, the resulting PDF has the image the correct size, but it has not been scaled. So the dimensions are correct, but only half of the image will be visible.
    To see what I mean, in Excel, add a picture, then choose Page Layout-Scaling and set to e.g. 50%. Check the print preview to see how it should look, and make sure you have a real printer selected in File-Print (NOT Adobe PDF printer). Then create PDF using the toolbar button. The image in the PDF will be wrong.
    This works fine if using native PDF converter (e.g. Save As PDF file) or by printing to the PDF printer, or by using the CreatePDF button when the Adobe PDF printer is selected as default in the print options.
    This seems to be a bug in X as in 9 it worked fine.
    Is there a solution to this?
    Thanks

    I should add, I updated to 10.1 and it did not resolve the issue.

  • Problems with image scaling

    I'm facing a real problem with image scaling
    I've used several algorithms but it all has defects but the most common thing is the out of memory error after several enlargments...
    does any one know a solution...
    note:
    I've used several packages to do so,but I'm looking for a solution from the jdk itself
    JAlexscorpio

    Did you take into account that the getScaledInstance() -method creates a completly new Image?
    So if you use it like in
    ImageIcon icon1=new ImageIcon("Blah.gif");
    ImageIcon icon2=new ImageIcon(icon1.getImage().getScaledInstance(400,400,SCALE_FAST);
    you will end up with 2 different Images which have their own data and memory requirements.
    even if you use something like
    ImageIcon icon1=new ImageIcon("Blah.gif");
    Image i=icon1.getImage();
    icon1.setImage(i.getScaledInstance(200,200,SCALE_FAST));
    You will need enough memory to store the data for the original image, as well as the data for the scaled
    version of the image, at least for the time that it take the JRE to create the scaled version. You never know when the garbage collector kicks in to delete you old data so it could be that this takes some time and until
    that moment your memory is not available. If your now doing several of the scaling operations, and there is no chance for the garbage collector to do its work, you will run out of memory.
    I hope that might help, if not feel free to post again

  • How to upload a image file using JSP

    hello to all.
    i am in the learning stage please help me to upload a image file
    using jsp. give the explanation to the code also if possible.
    thanks in advance
    sincerely
    Chezhian

    You may find the following articles useful for the JSP/Servlet part:
    Uploading files: http://balusc.blogspot.com/2007/11/multipartfilter.html
    Downloading files: http://balusc.blogspot.com/2007/07/fileservlet.html

  • How to get and display image file through servlet

    If I've got a jpg file on the server..
    How can I use servlet to return that image via the following calling method
    /displayfile?filename=image.jpg
    the image.jpg in the server will return
    I know that I need to set the content type to image/jpeg
    after that, how can I return the image file to browser?

    - Get the "file" Parameter from the URL QueryString
    - check if the File specified exists on your filesystem
    - read in the jpg from the file (best would be binary)
    - set the right Mime Type (as you already wrote)
    - write the filecontent to the ServletOutput as you would do with any other content
    - that's it.

  • How to create dynamic images in java servlets?

    I want to create dynamic images in java servlet. Can servlet create dynamic images that based on the input data files? The results can be displayed in GIF, JPG..format? how can this be done? any example in internet?
    What OS do I need to install and what other requirements needed if i want to build up a servlet server?
    Thanks a lot!

    Also worth having a look at SVG http://www.w3.org/TR/2001/REC-SVG-20010904/, you can get a viewer at http://www.adobe.com/svg/ or you can use Batik http://xml.apache.org/batik/index.html to convert SVG to other formats such as JPEG.
    HH

  • Displaying BLOB image by using ADF Faces

    Hi all,
    I digged the forum but couldn't find any satisfied answer about displaying BLOB images by using ADF Faces.
    I have insterted POJO object to Oracle database but couldn't find any way to display blob (in java byte [] ) data in POJO.
    I have read the POJO object from database which contains two field; one of them is id field and other is BLOB data which holds GIF or JPG image and I want to display this image another page which contains also other fields / records ...
    thanks for your answers
    regards...
    --baris                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    This thread at Sun : http://forum.java.sun.com/thread.jspa?threadID=513804&messageID=2445090
    talks about two options for creating a graphicImage jsf tag. (img tag)
    1. Make the img tag url refer to a servlet (instead of a static image file)
    2. Embed the image into the tag as inline base64 encoded data.
    2a. Use an <Object> tag with inline data.
    1. Looks a bit complex for a simple problem.
    2 and 2a don't work with some browsers.
    - And I've not yet figured out how to hook into the ADF Faces table-rendering logic to get it to add my image column. My table binds to a collection DataControl, [which in turn retrieves from a findAllItems call on a session facade, which uses my domain model, and wraps up access to a TopLink pesistence layer]. The framework just ignores my byte[] attribute when creating the jsf table from the DataControl. All string, int etc. attributes get represented correctly in the jsf table output.

  • VI Method "Front Panel:Get Image Scaled" Memory Error 17

    Hi all, I've got two almost identical sub vi front panels that I'm dumping to a jpg image for reporting purposes.  One was copied and slightly modified from the other to show a different data set and plot.  The original works just fine, but the second sub vi, when using the "Front Panel:Get Image Scaled" method to pass the image to write the jpg, always returns the following error:
    "Error 17 occurred at Invoke Node in Myprogram
    Possible reason(s):
    LabVIEW:  Not enough memory to manipulate image.
    =============================
    NI-488:  Unrecognized command.
    Method Name: Front Panel:Get Image Scaled
    [Continue] [Stop]  "
    I've stripped the problem section into a simple tiny new that only opens the report and tries to get the image with the same working/non-working result above.  Using the Execution Trace Highlighter, it error is definitely occuring when the Method executes.
    Any ideas?  Thanks.

    Hey cjgpr,
        I haven't been able to dig up much info on this error message.  There's one other discussion forum post that talked about it some, and a KnowledgeBase article on it.  It seems that whatever changes you made to the front panel have caused it to exceed your computer's memory when creating an image.  Try removing items until it works, then see what actually breaks the functionality.
    Brian B
    Field Sales Engineer
    Tennessee/Southern Kentucky
    National Instruments

  • Image scaling changes

    Before I started here, the team was using FrameMaker 8 and migrating to FM 10. During the migration, we noticed that images in the documents we opened, converting them to FM10, had their image scaling data changed.
    Typically, we acquire screen shots using the highest resolution screen supported - mine is currently set at 1440 x 900. We scale the images to a width of 510 pixels (optimally) but no more than 600 pixels in our screen capture utility. We save the screen shots as Grayscale JPEGs. This process has, historically, provided images that fit our text column flow perfectly.
    In previous versions of FM, the images imported by reference appeared as 100% scaling in the FM image properties. Now, they appear as 75% scaling. We're wondering why and if there is any effects we need to be aware of in terms of PDF and HTML Help file sizes.
    While testing the import process, looking to see if the FM scaling data affected the image size, we saw that the pixel dimensions given by SnagIt varied wildly from the pixel dimensions given by FM. For example, the SnagIt dimensions for one image indicated it was 505x493 pixels whereas FM gave the dimensions of the source file as 507x315 pixels. Both are, as far as I know, giving me the source file dimensions but they are different.
    We might not have noticed this, the images looked okay, but we were carefully going through the transition to FM10 and looking at every detail.
    Question: why is FM10 auto-scaling the images to 75%?
    Question: does this scaling do anything to our output that we need to be aware of?
    Question: why do we get two different dimension data from the two software packages?
    Thanks,
    Wanda

    We  save the screen shots as Grayscale JPEGs.
    Are the screen images contone (e.g. real-world photos, CGI imagery),
    or flat (e.g. dialogs, line art)? JPEG uses curve-matching compression,
    which is great for tones that vary smoothly, but introduces nasty ringing
    edge artifacts on sharp edges of flat tones.
    TIF(zip), uses repeat-count compression, and is both non-destructive to flat
    tone images, and often compresses them more efficiently. We use EPS
    for the import format (no compression) and let Distiller or Acrobat post
    determine the compression to use.
    This process has,  historically, provided images that fit our text column
    flow perfectly.In  previous versions of FM, ...
    What is the target delivery format?
    ... the images imported by reference appeared as  100% scaling in
    the FM image properties. Now, they appear as 75%  scaling.
    In case you want to try it, I have never seen imported EPS objects
    change size when migrating a document to a later rev of FM.
    We import using 96 dpi.
    If the target is PC screen display at 100% page size, that's probably a
    decent target. PC screen resolutions today probably range from 80 to
    110 dpi, and I'd guess that 96 is very close to the sweet spot.
    We use (and I favor) bringing in all contone content at 200 dpi or
    higher. We bring bitmap (bi-level line art) in at 600. But then our
    target media is 600 dpi B&W bitmap on paper. However, we like
    to give web readers of the PDFs reasonable detail in images.
    Apple's "Retina" crusade is trying to move the industry to 300 dpi
    displays. I'd be happy with 200.

  • Images exported using Leopard are soft compared to Tiger.

    I've been working on exporting images for client preview and noticed that the images I'm exporting under Leopard seem a bit soft. I checked my export settings and everything looks the same as it did under Tiger.
    For comparisons sake, I exported several images that had previously been exported under Tiger and there is a definite difference. Side-by-side, the images exported using Leopard are much softer than the images exported using Tiger. The edits on these images were all previously done using Tiger.
    Has anyone else noticed this?
    I'm using 1.5.6 on 10.5.1.
    Thank you!
    Cheers,
    Anthony
    Message was edited by: Barbatto - Fixed Subject Line

    Janet Taylor wrote:
    Everything looks fine for me from Aperture and LR. I did a clean install of Leopard and all my apps on a Macbook Pro. Are you looking at images in photoshop to compare them? Preview is not a reliable way to check for sharpness right now, since some rocket scientist decide it would be cool if you couldn't scale in set increments anymore, and the randomly scaled rendition can be very soft. As a follow-on to that thought, are the images on your web site displaying at the size you exported them at? If they're being scaled on the web page, and safari is using the same rendering engine as Preview, it's possible that it's making the images look soft.
    hope i said something useful.
    Hi Janet,
    Hmmm, perhaps the fresh install is the way to go? I'm using Photo Mechanic view the exported images, not Preview or Safari. I only mentioned Preview in an earlier thread because in other discussions I've found, Preview appears to exhibit some of the same softness that myself and a few others are experiencing with our Aperture exports.
    Here's a screen grab of two images rendered side-by-side in PhotoMechanic. The top image was exported using Tiger while the bottom image was exported using Leopard. The actual edits on the image (white balance, sharpness, etc) were done previously in Tiger. The only thing I did to the image in Leopard was export it.
    http://www.barbatto.com/misc/comparison.jpg
    In this example, it's pretty obvious that the image exported with Leopard is much softer. Also note that the file size is slightly smaller for the Leopard exported image.
    As for the images on my website, most of them were exported with Aperture under Tiger. Since I've upgraded to Leopard and have been experiencing soft images, I've been using Canon's Digital Photo Professional to export any newer shots I've placed on my site.
    Regarding Lightroom, I installed the trial and its exports were flawless. They don't exhibit any of the softness I am experiencing with Aperture.
    So, right now, I'm at a loss. I experience this softness on both my MacPro and MacBook Pro. It should be noted that both machines were upgraded. Perhaps I should take some time and do a clean install on one of the machines and see if my results are any different. Or keep my fingers crossed that 10.5.2 will solve my problems
    Thanks for your comments!
    Cheers,
    Anthony

  • Outputting JPEG using servlets

    hi
    Im trying to output the JPEG created by the StockGraphProducer class i found on Javaworld to a webpage using a servlet output stream.
    The original code used a file output stream i have included a snippet of it below. I have also included my servlet where i have tried to amend it to render JPEG to the webpage but im not usre abotu it or what bits i need to change in the StockGraphProducer
    I woudl be very grateful if someone could take a quick look at this .
    thanks
    public class StockGraphProducer implements ImageProducer
      private static int ImageWidth = 300;
      private static int ImageHeight = 300;
      private static int VertInset = 25;
      private static int HorzInset = 25;
      private static int HatchLength = 10;
       *  Request the producer create an image
       *  @param stream stream to write image into
       *  @return image type
    // i want to try and use a servlet output stream to send the JPEG to the user insteadof outputstream.
    public String createImage(Outputstream stream) throws IOException
        plottedPrices = new Point2D.Double[5];
        int prices[] =  {105, 100, 97, 93, 93};
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream);
    //do i remove the stream paaremter from createiamge and above function???
        BufferedImage bi = new BufferedImage(ImageWidth + 10,
                                             ImageHeight,
                                             BufferedImage.TYPE_BYTE_INDEXED);
        graphics = bi.createGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());
        graphics.setColor(Color.red);
        createVerticalAxis();
        createHorizontalAxis();
        graphics.setColor(Color.green);
        plotPrices(prices);
        encoder.encode(bi);
        return "image/jpg";
    public final class GraphRenderer extends HttpServlet
         public void doGet(HttpServletRequest request,
                               HttpServletResponse response)
           throws IOException, ServletException
              HttpSession session = request.getSession(true);
                   response.setContentType("image/jpeg");
              ServletOutputStream sos= response.getOutputStream();
      //the original code
       /* try
           FileOutputStream f = new FileOutputStream("stockgraph.jpg");
           StockGraphProducer producer = new StockGraphProducer();
           producer.createImage(f);
           f.close();
        catch (Exception e)
          e.printStackTrace();
    //i want to try and use a servlet output stream so that the JPEG is sent to the webpage     i tried the following butim not sure about it. I got rid of the outputstream parameter from StockGraphProducer and left it empty and tried .
              try
                   StockGraphProducer producer = new StockGraphProducer();
                          producer.createImage();
                   //i dont think i need this part.      
                   /*Dimension size= producer.getPreferredSize();
                   BufferedImage image = new BufferedImage((int)size.getWidth(),                (int)size.getHeight(), BufferedImage.TYPE_INT_RGB);
                   Graphics g= image.createGraphics();
                   gp.paint(g);*/
                   // Send back image i dont think this is correct
                   JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(sos);
                   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
                   param.setQuality(1.0f, false);
                   encoder.setJPEGEncodeParam(param);
                   encoder.encode(image);
              catch(Exception ex)
              {

    Hi,
    I need to create a program where I get an Image from DB and then display it in Browser using servlets.
    I was looking at the StockGraphProducer, but it seems the code is not fully posted.
    I would greatly appreciate anyone who has this StockGraphProducer program would email me or post it.
    Thanks in advance.
    my email address is [email protected]
    Again Thanks

  • Image scaling / memory 3 questions

    I hate to post this because I am sure there are a million posts about this, but I am still having a problem and it is taking tooooo long and I just cant find the solution. I am trying to scale images down to thumbnails. The images are really large and are consuming too much memory. Is there a way to scale the images and only retain the scaled bytes in memory rather than all of the image data.
    I am assuming this is still stored because my program runs out of memory after creating about 3 thumbnails of large images, but works fine for smaller ones. I am loading the images in a thread (one at a time).
    2. I tried to use the AffineTransformationOP and my images came out blueish? Anyone know about that. Not a major concern
    3. Is it possible just to store the graphics from an image and use that to paint the component and completely eliminate having the image left in memory? maybe..??
    persistantGraphics = image.creategraphics();
    persistantGraphics.drawImage(image,0,0,null);
    image = null;
    paintComponent(Graphics g){ g = persistantGraphics;}Here is my scaling code.
    BufferedImage image = ImageIO.read(theFile);
    public static BufferedImage percentScale(BufferedImage orig, double percent){
            if(orig == null){return null;}
            int transparent = orig.getColorModel().getTransparency();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            BufferedImage image = gc.createCompatibleImage((int)(orig.getWidth() * percent), (int)(orig.getHeight() * percent), transparent);
            Graphics2D g = image.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            AffineTransform xform = AffineTransform.getScaleInstance(percent, percent);
            g.drawRenderedImage(orig, xform);
            g.dispose();
            orig.flush();
            return image;
        }//end percentScale

    Image#getScaledInstance()

Maybe you are looking for

  • Copy Factors from Sales Order to Purchase Order

    Hello together, A customer of our company works with the factors because they have a lot of packages with a different count of pieces. They create automatically a Purchase Order on the basic sales order. But the problem is, that the factors are set t

  • I've lost the camera icon on the start screen.

    When I first started my 4S I had a camera icon next to the slider. It's gone now. How do I restore it?

  • Sleep, Passwords, and Scheduled Backups

    Okay, I have a question that I've yet to find an answer to (and I've looked high and low). I would think it would be a common issue, but perhaps not. I downloaded Deja Vu a few days ago to schedule backups for my computer. Ideally I'd like them to ru

  • Song not marked as explicit

    I was listening to some of my child's music and I heard cuss words in it but it was not marked as explicit. I was concerned because my child has almost 10 hours worth of music what can I do about this. Besides go though every one to check that there

  • Cells not rendering in JList

    The cells in my JList won't render. I'm using a custom renderer. I've created a basic example of my problem and included it here. package jds; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.util.Random; import