Image scaling problem

Hello,
I have been trying to scale an image to create a thumbnail. The thumbnail image size is around 200*200. The thumbnail is to be rendered on a web browser. My code is:
public static byte[] getScaledImage(InputStream imageData) throws IOException {
       Image origImg = ImageIO.read(imageData);
       int origImgHeight = origImg.getHeight(null);
       int origImgWidth = origImg.getWidth(null);
       int newImgHeight /*determined by custom logic*/;
       int newImgWidth /*determined by custom logic*/;
      /* code for determining newImgHeight and newImgWidth  keeping the aspect ratio */
       origImg = origImg.getScaledInstance(newImgWidth, newImgHeight,
                                           Image.SCALE_AREA_AVERAGING);
       BufferedImage bimage = null;
       bimage = new BufferedImage(origImg.getWidth(null), origImg.getHeight(null),
                                  BufferedImage.TYPE_INT_RGB);
       Graphics g = bimage.createGraphics();
       g.drawImage(origImg, 0, 0, null);
       g.dispose();
       ByteArrayOutputStream os = new ByteArrayOutputStream(10);
       ImageIO.write(bimage, "jpg", os);
       return os.toByteArray();
}The calling method is:
FileCopyUtils.copy(ImageUtils.getScaledImage(lobHandler.getBlobAsBinaryStream(rs, 1)),
                                      imageContent);here imageContent is the http response's outputstream.
Now the problem is the resulting image displayed on the web page becomes distorted. I first thought that this is due to the thumbnail size. But the scaling done by gimp does not distort the image.
I have also tried this:
BufferedImage thumbImage = new BufferedImage(newImgWidth, newImgHeight, BufferedImage.TYPE_INT_RGB);
       Graphics2D graphics2D = thumbImage.createGraphics();
       graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
       graphics2D.drawImage(origImg, 0, 0, newImgWidth, newImgHeight, null);instead of using getScaled instance.
What could be the problem? This is a problem I need to solve immediately. So I am at a loss. Please help me here.

Try scaling your source image like this:
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ScalingToSize {
    int W = 200;
    int H = 200;
    int SCALE_TO_FIT  = 0;
    int SCALE_TO_FILL = 1;
    private JPanel getContent(BufferedImage image) {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5,5,5,5);
        gbc.weightx = 1.0;
        panel.add(wrap(image), gbc);
        panel.add(wrap(scale(image, SCALE_TO_FIT)), gbc);
        panel.add(wrap(scale(image, SCALE_TO_FILL)), gbc);
        return panel;
    private BufferedImage scale(BufferedImage src, int style) {
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage dest = new BufferedImage(W, H, type);
        Graphics2D g2 = dest.createGraphics();
        if(style == SCALE_TO_FIT) {
            g2.setBackground(UIManager.getColor("Panel.background"));
            g2.clearRect(0,0,W,H);
        double scale = getScale(src, style);
        double x = (W - scale*src.getWidth())/2;
        double y = (H - scale*src.getHeight())/2;
        AffineTransform at = AffineTransform.getTranslateInstance(x, y);
        at.scale(scale, scale);
        g2.drawRenderedImage(src, at);
        g2.dispose();
        return dest;
    private double getScale(BufferedImage image, int style) {
        double xScale = (double)W/image.getWidth();
        double yScale = (double)H/image.getHeight();
        return (style == SCALE_TO_FIT) ? Math.min(xScale, yScale)
                                       : Math.max(xScale, yScale);
    private JLabel wrap(BufferedImage image) {
        ImageIcon icon = new ImageIcon(image);
        return new JLabel(icon, JLabel.CENTER);
    public static void main(String[] args) throws IOException {
        String path = "images/cougar.jpg";
        BufferedImage image = ImageIO.read(new File(path));
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new ScalingToSize().getContent(image));
        f.pack();
        f.setVisible(true);
}

Similar Messages

  • Image scaling problem with object handles

    Hi,
    I am facing scaling problem.I am using custom actionscript component called editImage.EditImage consists imageHolder a flexsprite which holds
    image.Edit Image component is uing object handles to resize the image.I am applying mask to the base image which is loaded into imageholder.
    My requirement is when I scale the editImage only the mask image should be scaled not the base image.To achieve this I am using Invert matix .With this
    the base image is not scaled but it  is zoomed to its original size.But the base image should not zoomed and it should fit to the imageholder size always. When I scale the editImage only the mask image should scale.How to solve this.Please help .
    With thanks,
    Srinivas

    Hi Viki,
    I am scaling the mask image which is attached to imageHolder.When i  scale
    the image both the images are scaled.
    If u have time to find the below link:
    http://fainducomponents.s3.amazonaws.com/EditImageExample03.html
    u work with this component by masking the editImage.If u find any solution
    for scale only mask ,plz share the same.
    thanks,
    Srinivas

  • Placed image scaling problem

    Hello,
    just need one advice from the gurus out here.
    i have placed few images in adobe indesign , now after placing image in indesign if i scale the image to 102 or 103 or 105% will it effect printing quality in offset printing ??? i mean i am increasing the size by 1% or 2% or 4% will it effect printing ? becuase scaling in photoshop is going to take lot of time because i have 1500 different products and all have different scaling issue so i thought of scaling bit more in indesign itself, please advice.
    regds
    Chako

    If you know what line screen you're printers is using then you can calculate your minimum PPI.
    The general rule has been to multiply the LPI x 2 = ppi | Which a lot of people take to assume that the LPI will be 150 in most cases, and that's where the 300 ppi for images originates.
    But in truth different mediums would use different line screens, like newspapers, magazines, high-end art books etc. And the x 2 rule is a safe play, but it really should be 1.41 (or 1.5 to keep  it simple).
    Newspapers generally at 85 - 105 lpi
    127.5ppi to 157.5 ppi
    Magazines generally around 133 - 150 lpi (some high end magazines may even use 175lpi)
    199.5 ppi to  225 ppi
    Art books - high end printing etc around 175 - 200 lpi.
    262.5 - 300 ppi
    But as a rule of thumb it's best to keep your print images at 300 ppi for printing - but you can go lower, check with your printers as to what they recommend if you really need an image to go below 300 ppi for printing.
    But the next time your printer tells you that your images are 250ppi and not good enough for printing you tell him that his halftone cells are rotated 45 degrees and that a2 + b2 = c2

  • 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

  • Image Scaling Bug?

    I've been working with flex for a few weeks now, and I've
    come across this odd behavior in the Image class. The livedocs
    state that the default value for the scaleContent property of an
    Image object is 'true'. This is the case, and when setting the
    width or height of my image it scales correctly. The problem is
    that the container that holds the object only scales with the
    explicitly set value and leaves the other as its original size.
    The following code is a small testcase to show the behavior
    in action.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Style>
    .test {
    cornerRadius: 0;
    headerHeight: 0;
    borderThickness: 1;
    dropShadowEnabled: false;
    borderStyle: solid;
    backgroundColor: #333333;
    borderColor: #ff0000;
    titleStyleName: "myTitleStyle";
    </mx:Style>
    <mx:Box styleName="test">
    <mx:Image source="glassdoor.jpg" height="32"/>
    </mx:Box>
    </mx:Application>
    You'll have to replace the image name with one that you
    provide, and set the height to something smaller that the image's
    height to see the effect. The box's red border shows that it
    realizes the image is 32 pixels in height, but doesn't seem to know
    what to do with the implicitly scaled width. Any ideas? Am I doing
    something wrong, or is this a bug? Since the box normally conforms
    to the size of the object inside it, I would have expected it to
    shrink on both parameters to continue hugging the outside of my
    newly-scaled image.

    The problem is that when the Box asks the Image for its size
    it can only report the explicity set height. When the Image tag
    loads its source it scales it to make the size you set (32 high)
    but doesn't change its width - it is the Image and not the Box that
    is causing what you see. The Image won't shrink to fit the image
    loaded. Try adding horizontalAlign="center" to the Image and see if
    the loaded source floats in the middle.
    Using horizontalAlign and verticalAlign on the Image tag
    aligns the actual image within the Image tag space. For example, if
    you have <mx:Image width="100" height="100"
    horizontalAlign="center" verticalAlign="middle" /> and you load
    in a 300x600 image, the image will be scaled to 50x100 and be
    centered within the 100x100 area of the Image tag.
    In general, if you cannot give an explicit size, give a
    minWidth or minHeight, so the measurement phase of the Flex
    component layout cycle has something to work with.

  • Scale image strange problem

    Hi
    I have loaded an image using MovieClipLoader and am using the following code to scale it to fit a photo frame:
    var mcLoader:MovieClipLoader = new MovieClipLoader();
    ..  add listeners ...
    mcLoader.loadClip(filePath, frame.imageHolder);
    function loadInitEventHandler(target_mc:MovieClip):Void
    var scale:Number = Math.min(frameWidth/target_mc._width * 100, frameHeight/target_mc._height * 100);
    target_mc._width = scale;
    target_mc._height = scale;
    The code works for most of the images except images with resolution 2880 x 2880.  It did not scale properly - part of the image on the right does not show. Please see images below.  The lower image scaled properly, but the upper one did not.
    The math seems to be correct and I do not know what the problem is.
    Any help is appreciated!
    Thanks in advance!

    I checked the resolution of the image on the web server.  It is more than 2880 x 2880.  I thought the image resolution was 2880 x 2880 at first because I run a trace and it says 2880 x 2880.  Probably Flash changes the resolution to 2880 x 2880.
    Thanks for the help!

  • 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

  • Preview scaling problem

    hello,,,
    I have a problem with preview when I try to scale Image; scaling not working -> image size remains without any change

    i'm having the same problem, when i change the scale, say to 100% like normal, average printing, the next time i print from preview, the scale is back up to something like 783%. it always fits it to the page, even though i have previously chosen to scale to 100%. is there a way to make it so i dont have to change the scale percentage and whatnot before printing? i've tried saving the settings but that only seems to work for the paper type, quality etc.

  • JPEG Image Scaling Speed

    I've got an application where I'm drawing images to the display from a TCP/IP stream. I'm unable to acheive much better than 8 or 9 fps and the real CPU consuming task seems to be the JPEG image scaling. The frames are being scaled by about 2x but the same color depth is retained. I'm running this application on a dual, 1 Ghz PIII with Red Hat 7.1 and JDK 1.3.1. Any suggestions on how to enhance the performance of Java's image scaling would be appreciated.

    You could try using bufferedImages and doing the scaling yourself. I can re-draw a bufferedImage by altering it's raster data
    ie..
    byte [] data = bi.getData().getDataBuffer().getData();
    I get up to 100 fps edditing a 640x480 area. You will have to account for things like bit depth yourself, and scaling algo's, but it might be worth it.
    Also check the Bug database, I believe your problem MAY be related to a bug where scaling always converts the entire image to format -> RGBA -> scaled format.

  • I have LR5 on a mac book pro with a external hard drive with LR5 images. my problem is my external hard corrupted reformatedand have to this is expensive and i would to start over in LR5

    i have LR5 on a mac book pro with a WD external hard drive with my with my LR5 images . my problem is my external drive is corrupted .i was told by apple that my macshow the hard drive is there but it is not moumting and have to be reformat. i have to use recovery data to save my images on my external before i can refomat.iam willing to lose my images on my extenal hard drive but i would like to know can i erase my LR5 images and start over or delete LR5 and download it again

    Simply start a new catalog:
    File >> New Catalog
    Choose a new name and save.
    When the empty catalog launches you are ready to start over.

  • My iMac 27" Late 2012 has Image Persistence Problem

    I'm wondering what to do about an annoying image persistence problem on my 27" late 2012 iMac. I got the iMac just a few days ago. Monday actually, so 4 days ago.
    It's the 3.4GHz i7, 8GB, NVIDIA 680MX 1TB fusion drive model.
    Overall it has become the love of my life, but the image persistence thing is getting harder to ignore. This happens after only a few minutes of use. If I follow Apple's instruction on dealing with LCD image persistence, I can make it go away for a while, but it comes back very quickly.
    It is extremely noticeable on a plan dark background. It looks as thought he screen has been left on for a very long time with the same windows open, but it occurrs in less than 5 minutes of use with nothing more intense than a bit of web surfing.
    I've read that this is happening a great deal on these new iMacs, particularly teh 27" machines.
    While the problem seems to be known to those of us afflicted I don't know if Apple has acknowledged an issue or not.
    Here is a sample of the complaints: http://forums.macrumors.com/showthread.php?t=1509571
    I can make the ghost image vanish by bringing up an all white scree for a minute or so or using LCD Scrub.
    I'm wondering if anyone else has foun a solution other than asking for a replacement computer, which Apple seems to be granting on this issue?

    Avoiding image persistence on Apple (IPS) displays
    Avoiding image persistence on Apple LCD displays
    If you cannot resolve the issue yourself, then return the computer for a replacement. You may do this freely within 14 days from date of purchase, so don't delay.

  • Problem: codebase, jar and image reloading problem please help!

    Hi Java Gurus,
    I have written an applet that extends JApplet for viewing webcam. In order to reduce the download time I put my classes into a doorcam.jar file. The following is my <applet> tag in my html file.
    <applet code="CameraApplet.class"
    archive="doorcam.jar"
         codebase = "webcam/classes"
         width="375" height="475">
    <param name="imagePath" value="http://judge/webcam/images">
    <param name="webCamImage" value="door.jpg">
    <param name="COMPort" value="COM2">
    <param name="frameRate" value="10"> <!-- could not exceed more than 10-->
    <param name="host" value="judge">
    </applet>
    The fist problem is that my class file does not get loaded from the jar file if i provide the "codebase" attribute as above. Instead the browser load every single class file from the webserver. This has some problem too. Coz the browser sometimes just thorough NullPointerException or ClassNotFoundException. After much of debugging I found out that the problem is the IE browser which seldom fails to load classes or image file from the server. If i referesh the browser the applet and all its classes loaded successfully and runs smoothly. This behaviour never occurs when running with "appletviewer".
    I wanted all my classes to be loaded from my jar file. After much of trial and error I found out that if i remove "codebase" attribute the browser loads the classes from my jar file and applet loads very fast. This is where the second problem comes in. The browser does not reload my webcam image file so that the webcam become alive with live images, like before.
    If I run on "appletviewer" everything works fine my web cam is displayed properly. But in IE browser the image does not get reloaded when I refresh my image to give live to my webcam display. The refresh method is given below.
    private void refresh(final URL url) {
    Image webCamImage =getImage(url);
    webCamImage.flush(); // flush out the previous image
    webCamImage = getImage(url); // get a new image
    webCamImageIcon.setImage(webCamImage); webCamImageIcon.paintIcon(webCamLabel, webCamLabel.getGraphics(), 15, 15);
    When I add the "codebase" attribute back, the image gets reloaded for every refresh() and everything works fine. But the classes are also loaded from the server. And occasionally also suffers Class loading and image loading problem. As I presented earlier, when I do refreshing in the browser everything gets loaded and the applet function correctly with web cam displaying very well.
    The problem is so strange that I could not find any way to solve it.
    It would be a great help to me if somebody provide me some work around to the problem.
    I tested on Windows 2000, Windows XP, IE 5.5, IE 6 with J2SDK 1.4.0.
    Thank you all very much in advance.
    best regards,
    Judge

    Thank you so much for the suggestions. I did tried the way u suggested. The problem still the same.
    I think its the problem between IE browser and Java Plug-in.
    I which SUN would find these incompatibilities and solve these problems.
    I even tried using java SDK and plug-in 1.4.1 it even worst. It can't even load an applet. And it does not show any loading messages nor any error messages. It just show a cross sign on the upper left coner.
    I would be so glad, if Sun would try to eliminate the inconsistancies such as caching, loading, initializing etc between browser and its Java plug-In. For example, applets behave well in appletviewer and behave unpredictably in browser environment.
    I have seen so many people in the forums with all sorts of problems because of this.
    Right now I m desperately looking for work around to my problem.
    If somebody would provide me with the solution to my problem it would be a great help to me.
    thank you all so much.
    best regards,
    Judge

  • SSRS indicator image display problem!!

    Hello ALL;
    I am having problem with displaying indicator image in DEV report manager. but same rdl works in QA environment. Both server has SP1 installed. Any Idea? Appreciate for your help. Thanks,

    Hi Techchi,
    Based on the limited information, I cannot figure it out for this issue. As per my understanding, I think this issue can be caused by the browser that run the report manager. If you use IE explorer to render the report, I suggest that you can try to run
    it in compatibility mode. If you are using another browser, I recommend that you should use IE explorer to render the report to check the issue again.
    If this issue still exists, in order to solve the problem more efficiently, I need to clarify some information.
    Are all reports with indicator image cannot render well in DEV report manager? Or just this one report?
    What is the phenomenon about the indicator image display problem? Could you please post a screenshot about this?
    It is benefit for us to do further analysis. Thank you for your understanding.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • ComboBoxRenderer with image scaling

    hi all,
    I would like to know how to make the comboBoxRender with image scaling. Because my combo box is smaller than the image that I want to put inside..
    currently, I "extends JLabel implements ListCellRenderer", but if I call setIcon to the Label, it is not scale to the combo size..., so I think is it need to extends another type of component ?
    Could some of you give me a suggestion , better provide me a simple code.. Many Thanks for help.

    Hi,
    I've extended the Icon framework to support scaling. I never tried it with cell renderers, but maybe it works:
    Extend JXIconLabel, set the zoomingStrategy to FullZooming.RESPECTING_ASPECT_RATIO_INSTANCE and set the XIcon (eg. a XImageIcon).
    Maybe it works. (The library is open source.)
    http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JXIconLabel.html
    Homepage:
    http://www.softsmithy.org
    Download:
    http://sourceforge.net/project/showfiles.php?group_id=64833
    Source:
    http://sourceforge.net/svn/?group_id=64833
    http://softsmithy.svn.sourceforge.net/viewvc/softsmithy/trunk/lib/src/org/softsmithy/lib/
    API:
    http://softsmithy.sourceforge.net/lib/docs/api/index.html
    If you have questions just ask me!
    -Puce

  • Having a image alignment problem using clearbox

    Hi,
    I'm having an image alignment problem. I cannot figure it out. I'm using the clearbox - lightbox dreamweaver widget. Using Dreamweaver CS6.
    Actual page located here. Any help would be appreciated.
    http://dirtysouthink.com/gallery/dustin2.html

    This has very little to do with Dreamweaver. DW is merely a tool to assist you in building a web site. It is purely a matter of styling (CSS).
    When I look at the structure, I see
    BODY-CONTENT (width: 490px)
         GALLERY (width: 452px)
              CONTAINER (width: 500px)
                   ITEM (width: 150px)
    From this I can deduce that:
    GALLERY will fit inside BODY-CONTENT
    CONTAINER will NOT fit inside GALLERY or BODY-CONTENT
    ITEM will fit three times into CONTAINER
    To start with, I would reduce the size of the CONTAINER so that it fits inside of its parent. Then I would adjust the width of the ITEM so that only two of them fit inside of the CONTAINER.

Maybe you are looking for

  • I cannot download Photoshop CC to my PC. It fails at 43% download with request to close Adobe Bridge. However Bridge is not open. I successfully downloaded LightRoom CC.

    I cannot uninstall Bridge from my CS4 without installing Photoshop as well. I don't want to lose CS4 until I know I have CC installed successfully yet Photoshop CC will not download because there apears to be a conflict with CS4 Bridge. Advice would

  • Banshee and iPod sync

    I've searched everywhere and it looks like I'm either the only person unable to sync my iPod (add music and playlists) with Banshee, or I'm the only person trying it. Banshee sees my iPod - but I cannot add new files to it, and although it allows me

  • Ordering BT Infinity (Lead Times)

    Hello, I am renovating my new property and I am planning to move-in in around 6 - 8 weeks. I am led to believe that lead times to get a BT infinity engeneer in to install the broadband is around 2 - 3 weeks. I am happy to order it as soon as possible

  • Net bill value - why not possible in SAP

    hai, I have one basic doubt. Why SAP is not showing the balance amount of the bill? ex bill value is Rs.10000.00 partpayment received Rs.5000.00  in sap for partpayment, the saparate document is creating but it is not deducting the bill amount. Why i

  • Safari not displaying website comments

    Since the latest update to Safari in Mavericks 10.9.4, I no longer can see comments to articles at huffington post. When I open the same page in another browser, the comments are there. Anyone know a way to fix this?