Java 2D image resize...

Hi there...
I'm working with JMF to capture images from an IP Camera. And this is kinda done.
My problem now, it that, before I should work with the frames I get, I need to resize the images to certain dimensions, and this is indeed a big problem. I need a very fast way to resize large images to much smaller ones. I need to rescale up to 100 images per second.
Can u give me some advice? Can it be done better with Java 2D or JAI better than the traditional ways I found till now: AffineTranform & BufferedImage.getGraphics().drawImage() ?
I'm not that interested in image quallity because after resing, I also pass it though a series of filters to remove the noise. (No don't think that I can remove big noise... so some quallity is required also :( unfortunately)
I get the images as BufferedImage. Please help!

public static void main(String args[]) throws Exception {
        mjpegGrabber gb = new mjpegGrabber("http://192.168.2.5/now.jpg");
        gb.connect();
        BufferedImage im = gb.readJPEG();
        gb.disconnect();
        ImageIO.write(im, "png", new File("E:\\01.png"));
        BufferedImage im2 = null, im3 = null, im4 = null, imm = null;
        long time = System.currentTimeMillis();
        im2 = resize1(im);
        System.out.println("im2: " + (System.currentTimeMillis() - time));
        ImageIO.write(im2, "png", new File("E:\\02.png"));
        time = System.currentTimeMillis();
        im3 = resize2(im);
        System.out.println("im3: " + (System.currentTimeMillis() - time));
        ImageIO.write(im3, "png", new File("E:\\03.png"));
        time = System.currentTimeMillis();
        im4 = resize3(im);
        System.out.println("im4: " + (System.currentTimeMillis() - time));
        ImageIO.write(im4, "png", new File("E:\\04.png"));
    public static BufferedImage resize1(BufferedImage im) {
        BufferedImage im2 = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);
        Graphics2D destGraphics = im2.createGraphics();
        destGraphics.setRenderingHint(
                RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        destGraphics.drawImage(
                im,
                0, 0, im2.getWidth(), im2.getHeight(),
                0, 0, im.getWidth(), im.getHeight(),
                null);
        return im2;
    public static BufferedImage resize2(BufferedImage im) {
        BufferedImage im3;
        AffineTransform tx = new AffineTransform();
        tx.scale((double) 320 / im.getWidth(), (double) 240 / im.getHeight());
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        im3 = op.filter(im, null);
        return im3;
    public static BufferedImage resize3(BufferedImage im) {
        Image ima = im.getScaledInstance(320, 240, BufferedImage.SCALE_FAST);
        BufferedImage im4 = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
        im4.getGraphics().drawImage(ima, 0, 0, null);
        return im4;
    }For me fastes was resize2. Eearlyer I was using it with TYPE_BICUBIC, and that method realy takes its time...

Similar Messages

  • Image Resizing Using Java

    Hi.
    I am new to Java and have a question.
    I have an image at this path: "c:\images\pic1.gif".
    I want to take this image, resize it, and save it to a different path.
    I don't have any outside Toolkits.
    How do I do this?
    Or, more simply, how do I use the Image and BufferedImage classes?
    I cannot figure out how to create a BufferedImage object using the path for the image I have.
    Thanks in anticipation.

    the article referred by previous answer is pretty good, but you can do it simpler. Just:
    1. create buffered image
    2. get graphics
    3. draw your source image in the graphics with desired size
    Check for an implementation
    http://mediachest.sourceforge.net/download/MediaChest11-80.zip

  • Image resize : loss of quality by using Java API. What's wrong ?

    We actually have a problem with the resizing of pictures.
    We use jdk 1.4.2.
    We are trying to transform some picture from approx. 2000*1600 to 500*400.
    The result is poor (loss of colors, blur ...)
    We use an affineTransform and some renderingHints.
    There is actually no effect when we change the renderingHints parameters. Why ?
    Here's the code we use:
    import java.awt.geom.AffineTransform;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import java.awt.*;
    import javax.swing.*;
    public class Jpeg
        public Jpeg()
        // i  = la largeur de l'image redimensionner
        // s  = le chemin d'acces � l'image original
        // s1 = le chemin d'acces � l'image retaill�e
        public boolean resize(int i, String s, String s1)
           try
                File file  = new File(s);
                File file1 = new File(s1);
                //Parametrage de la lecture
                ImageIO.setUseCache (true);
                BufferedImage src = ImageIO.read(file);
                double d  = src.getWidth();
                double d1 = src.getHeight();
                double d2 = i;
                double d3 = d2 / d;
                if(d1 * d3 > d2)
                    d3 = d2 / d1;
                if(d3 > 0.8D)
                    d3 = 1.0D;
                int j = (int)(d * d3);
                int k = (int)(d1 * d3);
             AffineTransform  tx = new AffineTransform ();
                tx.scale (d3, d3);
                RenderingHints  rh = new RenderingHints (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                rh.put (RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                rh.put (RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                rh.put (RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                rh.put (RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                rh.put (RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
                rh.put (RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                AffineTransformOp  op    = new AffineTransformOp (tx, rh);
                BufferedImage      biNew = new BufferedImage (j, k, src.getType ());
                op.filter(src, biNew);
                ImageIO.write (biNew, "jpg", new File (s1));
            catch (Exception  e)
                e.printStackTrace ();
                return  false;
            return  true;
        public static void main(String args[])
            Jpeg jpeg = new Jpeg();
            jpeg.resize (Integer.parseInt (args [0]), args[1], args[2]);
    }Here's the original picture http://193.252.12.20/bugimage/14457.jpg
    Here's the resized picture http://193.252.12.20/bugimage/bur.jpg
    Here's the paintshop pro resized picture http://193.252.12.20/bugimage/psp.jpg
    Is there another way to resize pictures ?
    Can we have a better result by using jdk 1.5.0 ?
    Thanks for your help.

    Nothing wrong - it's a feature :).
    "Loss of colours" is connected with Java embedded JPEG decoder. If you transcode to for example PNG format using any image processing program and then resize using Java then colors will be OK.
    "Blur..." is connected with bad implementation of interpolation algorithms in JDK/JRE and can't be fixed :)
    I'm close to finish developing own resizing library which produced the next results from your image (it's a very good image to test). "from_png" means that the source image is PNG.
    <b>Box interpolation</b> (also known as nearest neighbour, but it's the honest implementation, not JDK fake):
    http://www.chainline.com/Box.jpg
    http://www.chainline.com/Box_from_png.jpg
    Well-known <b>Lanczos 3</b>:
    http://www.chainline.com/Lanczos_3.jpg
    http://www.chainline.com/Lanczos_3_from_png.jpg
    Not-well-known <b>Ideal 5S</b> but one of the most qualified:
    http://www.chainline.com/Ideal_5S.jpg
    http://www.chainline.com/Ideal_5S_from_png.jpg
    And 2 interesting s.c. "sharp" filters which make the result sharpen:
    <b>Sharp Light 5</b>:
    http://www.chainline.com/Sharp_Light_5.jpg
    http://www.chainline.com/Sharp_Light_5_from_png.jpg
    <b>Sharp 5</b>:
    http://www.chainline.com/Sharp_5.jpg
    http://www.chainline.com/Sharp_5_from_png.jpg

  • Image-resize servlet

    Hi,
    I�ve been working on an image-resizing servlet on and off for quite some time now, and I just cant seem to get it to load the image correctly.
    I guess its very simple once you figure it out. The following is the interesting part:
    Image image = Toolkit.getDefaultToolkit().getImage("../pictures/pic" + pictureId + ".jpg");
    MediaTracker tracker = new MediaTracker( new JFrame() );
    tracker.addImage(image, 1);
    // Load image
    try {
      tracker.waitForAll();
    } catch (InterruptedException e) {}
    // Scale image
    image = image.getScaledInstance(width, height, Image.SCALE_DEFAULT);I then copy the Graphics from the Image to another Graphics before it is sent to the client (have some cache-stuff going on in the middle), but all images turn out beeing plain black.
    Anyone with ideas/sample code?

    hi flaperman
    i did something similar in my resizing servlet:
    BufferedImage image = ImageIO.read(new File(path));
    Image im = image.getScaledInstance(width, height, Image.SCALE_FAST);
    BufferedImage thumbnail = toBufferedImage(im);
    ImageIO.write(thumbnail, "jpeg", response.getOutputStream());
    i found the code of the method toBufferedImage() on the following page http://developers.sun.com/solaris/tech_topics/java/articles/awt.html
    maybe this will help you. but i'm afraid it is slow and it seems to be leaking memory (a lot).
    cheers

  • How to make image resizable using mouse ?

    Hi,
    I want to know about that how to resize image by using mouse in Java Canvas. I created some tools like line, free hand, eraser. And want to know how to make an image resizable in canvas by using mouse. An image is jpeg, png, or gif format. I want to make image stretch and shrink by using mouse.
    Please help me..
    Thnax in advance.
    Manveer

    You make a listener to handle the mouse event that you want to capture, then program the affect you want using the event as the trigger.

  • JScrollPane image resizing

    Hi, i've a JScrollPane into my class "Scroll image" I want that the imageicon automatically is resized when i move the border of JscrollPane, i do not suceed to do this. help me.
    <code>
    * scroll_image.java
    * Created on 31 maggio 2004, 13.26
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.geom.*;
    public class scroll_image extends JPanel implements ChangeListener{
    JScrollPane si;
    int max_w = 300 ;
    int max_h = 300;
    ImageIcon def;
    JLabel et;
    ImageIcon tmp;
    BorderLayout lay = new BorderLayout();
    public scroll_image(BufferedImage buf) {
    this.setLayout(lay);
    tmp = new ImageIcon(buf);
    Image im = tmp.getImage();
    Dimension d = getScaledSize(tmp);
    def = new ImageIcon (im.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH) ) ;
    et = new JLabel(def);
    et.setBounds(0, 0, d.width, d.height);
    si = new JScrollPane(et);
    si.revalidate();
    si.setVisible(true);
    add (BorderLayout.CENTER, si);
    this.revalidate();
    this.setVisible(true);
    private Dimension getScaledSize(ImageIcon image) {
    double imageRatio =
    (double)image.getIconWidth() / (double)image.getIconHeight();
    if ( imageRatio > 1.0)
    return new Dimension( max_w,(int)(((double)max_h)/imageRatio) );
    else
    return new Dimension( (int)(((double)max_w)*imageRatio), max_h );
    public scroll_image get_scroll_image (){
    return this;
    public void paintComponent (Graphics g){
    setOpaque(false);
    revalidate();
    Dimension ddd = this.getSize();
    g.drawImage(def.getImage(), 0, 0, ddd.width, ddd.height, null);
    public void stateChanged(javax.swing.event.ChangeEvent ae) {
    revalidate();
    paintComponent(getGraphics());
    </code>
    How many errors i've done? where?
    Thank you.

    That was a joke referring to the fact that you posted the same message many times.
    I don't understand your requirements for a JScrollPane, but here is a resizable icon:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ResizableImageIcon implements Icon {
        private BufferedImage original, latest;
        public ResizableImageIcon(BufferedImage original, JLabel label) {
            if (original == null)
                throw new NullPointerException();
            this.original = this.latest = original;
            setIconFor(label);
        //ICON METHODS
        public int getIconWidth() {
            return latest.getWidth();
        public int getIconHeight() {
            return latest.getHeight();
        public void paintIcon(Component c, Graphics g, int x, int y) {
            AffineTransform xform = AffineTransform.getTranslateInstance(x,y);
            ((Graphics2D)g).drawRenderedImage(latest, xform);
        //CLASS METHODS
        public void setMaxSize(int w, int h) {
            if (w == getIconWidth() && h == getIconHeight())
                return;
            double factor = Math.min(w/(double)original.getWidth(), h/(double)original.getHeight());
            latest = ImageUtilities.getScaledInstance(original, factor, null);
        private void setIconFor(JLabel label) {
            label.setIcon(this);
            label.addComponentListener(new ComponentAdapter(){
                public void componentResized(ComponentEvent e) {
                    JLabel l = (JLabel) e.getComponent();
                    Insets insets = l.getInsets();
                    int w = l.getWidth() - insets.left - insets.right;
                    int h = l.getHeight() - insets.top - insets.bottom;
                    setMaxSize(w, h);
                    l.setIcon(ResizableImageIcon.this); //causes repaint?
                    l.repaint();
        //SAMPLE
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            JLabel label = new JLabel((Icon)null);
            label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            new ResizableImageIcon(ImageIO.read(url), label);
            JFrame f = new JFrame("ResizableImageIcon");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(label);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }And here is the utility code.
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ImageUtilities {
        public static void loadImage(Image image, Component c) {
            try {
                if (image instanceof BufferedImage)
                    return; //already buffered
                MediaTracker tracker = new MediaTracker(c);
                tracker.addImage(image, 0);
                tracker.waitForID(0);
                if (MediaTracker.COMPLETE != tracker.statusID(0, false))
                    throw new IllegalStateException("image loading fails");
            } catch (InterruptedException e) {
                throw new RuntimeException("interrupted", e);
        public static ColorModel getColorModel(Image image) {
            try {
                PixelGrabber gabby = new PixelGrabber(image, 0, 0, 1, 1, false);
                if (!gabby.grabPixels())
                    throw new RuntimeException("pixel grab fails");
                return gabby.getColorModel();
            } catch (InterruptedException e) {
                throw new RuntimeException("interrupted", e);
        public static BufferedImage toBufferedImage(Image image, GraphicsConfiguration gc) {
            if (image instanceof BufferedImage)
                return (BufferedImage) image;
            loadImage(image, new Label());
            ColorModel cm = getColorModel(image);
            int transparency = cm.getTransparency();
            int w = image.getWidth(null);
            int h = image.getHeight(null);
            if (gc == null)
                gc = getDefaultConfiguration();
            BufferedImage result = gc.createCompatibleImage(w, h, transparency);
            Graphics2D g = result.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            return result;
        public static GraphicsConfiguration getDefaultConfiguration() {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            return gd.getDefaultConfiguration();
        public static BufferedImage copy(BufferedImage source, BufferedImage target, Object interpolationHint) {
            Graphics2D g = target.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolationHint);
            double scalex = (double) target.getWidth() / source.getWidth();
            double scaley = (double) target.getHeight() / source.getHeight();
            AffineTransform at = AffineTransform.getScaleInstance(scalex, scaley);
            g.drawRenderedImage(source, at);
            g.dispose();
            return target;
        public static BufferedImage getScaledInstance2D(BufferedImage source, double factor, Object interpolationHint, GraphicsConfiguration gc) {
            if (gc == null)
                gc = getDefaultConfiguration();
            int w = (int) (source.getWidth() * factor);
            int h = (int) (source.getHeight() * factor);
            int transparency = source.getColorModel().getTransparency();
            return copy(source, gc.createCompatibleImage(w, h, transparency), interpolationHint);
        public static Image getScaledInstanceAWT(BufferedImage source, double factor, int hint) {
            int w = (int) (source.getWidth() * factor);
            int h = (int) (source.getHeight() * factor);
            return source.getScaledInstance(w, h, hint);
        //best of breed
        public static BufferedImage getScaledInstance(BufferedImage source, double factor, GraphicsConfiguration gc) {
             if (factor >= 1.0)
                 return getScaledInstance2D(source, factor, RenderingHints.VALUE_INTERPOLATION_BICUBIC, gc);
             else {
                 Image image = getScaledInstanceAWT(source, factor, Image.SCALE_AREA_AVERAGING);
                 return toBufferedImage(image, gc);
    }

  • Image resize after form upload

    I've a form where it's possible to upload an image.
    Now I want to resize that image to a particular size.
    I can do the job at command line, but when I use that code into my jsp, it doesn't work!
    For Example:
    <%@ page import="java.awt.*" %>
    <%@ page import="java.awt.image.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="com.sun.image.codec.jpeg.*" %>
    <%
    String imageFrom = request.getParameter("from");
    String imageTo = request.getParameter("to");
    int finalwidth = 100;
    int finalheight = 140;
    Image img = getToolkit().getImage(originalImage);
    %>
    this is the error, 'cause it can't find the getToolkit() function:
    [ Method getToolkit() not found in class etc etc ]
    Any suggestion?

    Thanks for the post. I have tried what you suggested, and I am getting an error:
    java.lang.RuntimeException: - Unable to render RenderedOp for this operation.
         at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:813)
         at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:853)
         at javax.media.jai.RenderedOp.getWidth(RenderedOp.java:2135)
         at image0test_0process__jsp._jspService(/test.jsp:42)
    and line 42 corresponds to:
    float imgW = imgOp.getWidth() + 0.0f;
    and the server's system.out has:
    java.lang.ArrayIndexOutOfBoundsException
    at java.awt.image.SinglePixelPackedSampleModel.setPixels(SinglePixelPackedSampleModel.java:602)
    at java.awt.image.WritableRaster.setPixels(WritableRaster.java:445)
    at java.awt.image.WritableRaster.setRect(WritableRaster.java:367)
    at java.awt.image.WritableRaster.setRect(WritableRaster.java:321)
    at com.sun.media.jai.codecimpl.JPEGImage.<init>(JPEGImageDecoder.java:146)
    at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:51)
    at com.sun.media.jai.opimage.CodecRIFUtil.create(CodecRIFUtil.java:89)
    at com.sun.media.jai.opimage.JPEGRIF.create(JPEGRIF.java:52)
    at java.lang.reflect.Method.invoke(Native Method)
    at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
    at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1669)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
    at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
    at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:104)
    at java.lang.reflect.Method.invoke(Native Method)
    at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
    at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1669)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
    at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
    at com.sun.media.jai.opimage.FileLoadRIF.create(FileLoadRIF.java:109)
    at java.lang.reflect.Method.invoke(Native Method)
    at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
    at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1669)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
    at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
    at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:805)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:853)
    at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:874)
    at image0test_0process__jsp._jspService(_test__jsp.java:74)
    java.lang.reflect.InvocationTargetException: java.lang.RuntimeException: Unable to process image stream, incorrect format.
    at com.sun.media.jai.codecimpl.JPEGImage.<init>(JPEGImageDecoder.java:114)
    at com.sun.media.jai.codecimpl.JPEGImageDecoder.decodeAsRenderedImage(JPEGImageDecoder.java:51)
    at com.sun.media.jai.codec.ImageDecoderImpl.decodeAsRenderedImage(ImageDecoderImpl.java:148)
    at com.sun.media.jai.opimage.StreamRIF.create(StreamRIF.java:135)
    at java.lang.reflect.Method.invoke(Native Method)
    at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
    at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1669)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
    at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
    at com.sun.media.jai.opimage.FileLoadRIF.create(FileLoadRIF.java:109)
    at java.lang.reflect.Method.invoke(Native Method)
    at javax.media.jai.FactoryCache.invoke(FactoryCache.java:130)
    at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1669)
    at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:481)
    at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:340)
    at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:805)
    at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:853)
    at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:874)
    at image0test_0process__jsp._jspService(_test__jsp.java:74)
    Looking at that I would guess that the image is in the wrong format, but I have tried it with many different jpg files that otherwise work fine. Is there something missing from the code?
    Thanks.

  • Image Resizing Problem

    Hello,
    I am working on image project. The task which I want to do is to resize the image. I am using normal java.awt.image package. The classes which I am using are AffineTransformOp for scaling an image, Graphics and BufferedImage etc. The problem is when I scaled down an image of large image to low image (e.g. 800 x 800 to 160x160), The image gets blued or some pixels are looking stretched. I have tried severl other 3rd party APIs but failed. However if i conver 400x400 image to 160x160 .. it works fine. I need quick help..plz if somebody can suggest any solution..
    Thanks

    try {
         AffineTransformOp op = null;
    BufferedImage tempImage;
    double xScale = (double)((double)x/(double)width);
    double yScale = (double)((double)y/(double)height);
              BufferedImage outImage;
              OutputStream os;          
    op = new AffineTransformOp(AffineTransform.getScaleInstance(xScale,yScale),AffineTransformOp.TYPE_BILINEAR);     tempImage = op.filter(original, null);           
    } catch (ImagingOpException e) {
    e.printStackTrace();
    System.out.println("Exception while creating imgages");
         }

  • Image Resize: InputStream - BufferedImage

    Hi,
    I'm in a position where I'm forced to use Java SE 1.3.1_19. We use Oracle 9iAS and aren't in a position to upgrade at present.
    I know in JavaSE1.5 I can use ImageIO etc to resize images on the fly because I have written a class to do this. How can I replicated this functionality in 1.3.1_19?
    My requirements are to upload via a multipart form (using Org.Apache.Commons.FileUpload) an Image to a BLOB field in an Oracle DB. If any one can suggest a way to do this with v1.3.1_19 I would very much appreciate it.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.swing.*;
    public class ScalingTest {
        private JScrollPane getContent() {
            Image orig = loadImage();
            BufferedImage scaled = getScaledImage(orig, 0.50);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weightx = 1.0;
            panel.add(new JLabel(new ImageIcon(orig)), gbc);
            panel.add(new JLabel(new ImageIcon(scaled)), gbc);
            return new JScrollPane(panel);
        private Image loadImage() {
            String path = "images/cougar.jpg";
            InputStream is = getClass().getResourceAsStream(path);
            byte[] imageData = readData(is);
            ImageIcon icon = new ImageIcon(imageData);
            Image image = icon.getImage();
            // ImageIcon does not let you know if the image was not
            // successfully loaded so you must ask it for feedback.
            int status = icon.getImageLoadStatus();
            String result = "";
            switch(status) {
                case MediaTracker.ABORTED:
                    result = "ABORTED";
                    break;
                case MediaTracker.ERRORED:
                    result = "ERRORED";
                    break;
                case MediaTracker.COMPLETE:
                    result = "COMPLETE";
                    break;
                default:
                    result = "unexpected loadingStatus: " + status;
            System.out.println("Loading status for \"" + path + "\": " + result);
            return image;
        private byte[] readData(InputStream is) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                byte[] buffer = new byte[4096];
                int len, count = 0;
                while((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                    count += len;
                is.close();
                System.out.println("image size = " + count);
            } catch(IOException e) {
                System.out.println("read error: " + e.getMessage());
            return baos.toByteArray();
        private BufferedImage getScaledImage(Image image, double scale) {
            int w = (int)(scale*image.getWidth(null));
            int h = (int)(scale*image.getHeight(null));
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
            g2.drawImage(image, at, null);
            g2.dispose();
            return out;
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ScalingTest().getContent());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Proportional Image Resizing

    Hi,
    Description of the task:
    I need to upload two images one is a full image and the other is a thumbnail representation of the same image of type jpg. I also need to ensure that all the uploaded images are within a given maximun size. For example:
    Thumbs should be 76 x 55 pixels
    FullSized should be 247 x 183 pixels
    Task Achievements:
    I've used the apachee commons package's FileItem class to handle retrival and storage of the image from the submitting servelet form.
    Description of the Problem:
    Don't know how to apply a proportional resize on the uploaded files (images) before storing them.
    Other Questions:
    1. Will the fact that conventional Buffered approach for reading files being not used hamper file manipulation?
    2. Can a proportional Image resizing function be applied to images in java. (Similar to that of php)
    3. Can an external php file be called or accessed from within java (a servlet) to perform the same functions of uploading an image and resizing it porportionally.

    private void uploadThumbImage(FileItem thumbImage, int eventId) throws JspException
         // code for fikle uploade goes here
         try
          //write the orginalFiles
          thumbImage.write(orginalThumbNail);
          resizeThumb(eventId);
         catch(Exception e)
             ErrorPrinter(e.getMessage()+" Exception in Image Upload");
    private void resizeThumb(int eventId) throws JspException
         try
              File loc = new File ("c:/"+eventId+".jpg");
              BufferedImage storedImage = ImageIO.read(loc);
              //ASSIGN  MAXIMUM X AND Y FOR STORAGE
              //1. set the expected allowable x and y maximum
              double maxiumX = 75;
              double maxiumY = 55;
              //2. check that the image is not too long or too wide
              double imgHeight = storedImage.getHeight()*1.0;
              double imgWidth = storedImage.getWidth()*1.0;
              if (imgHeight > maxiumY*2 && imgWidth > maxiumX*2)
                maxiumX = maxiumX*1;
                maxiumY = maxiumX*1;
              else if (imgHeight > maxiumY*2)
                maxiumY = maxiumY*2;
              else if (imgWidth > maxiumY*2)
                maxiumX = maxiumX*2;
              //3. Scale for the width (x)
              if (imgWidth > maxiumX)
               imgHeight = imgHeight*(maxiumX/imgWidth);
               imgWidth = maxiumX;
              //4. Scale for the lenght (l)
              if (imgHeight > maxiumY)
                   imgHeight = maxiumY;
                   imgWidth = imgWidth*(maxiumY/imgHeight);
              Image testImage = storedImage.getScaledInstance((int)imgWidth,(int)imgHeight,Image.SCALE_AREA_AVERAGING);
              BufferedImage biRescaled = toBufferedImage(testImage, BufferedImage.TYPE_INT_RGB);
              if (loc.exists())
                   if(!loc.delete())
                        ErrorPrinter("File that already exisits with file name could not be removed - (Thumbnail)");
              ImageIO.write(biRescaled, "jpg", new File ("c:/et_"+eventId+".jpg"));
              catch (IOException e)
                   ErrorPrinter(e.getMessage()+" Exception in Image Resize");
              catch(Exception e)
                   ErrorPrinter(e.getMessage()+" Exception in Image Resize");
    private static BufferedImage toBufferedImage(Image image, int type)
            int w = image.getWidth(null);
            int h = image.getHeight(null);
            BufferedImage result = new BufferedImage(w, h, type);
            return result;
       }

  • Image resize problem in Swing Application

    Hi All
    I need a help on resizing and adjustment of Image in Swing application.
    I am developing a Swing Application. There I am displaying a image on header.
    I am finding it difficult to manage the image, as I want the image to perfectly fit horizontal bounds(Even on window resize).
    The current code given below is unable to do so.. Even it's not able to fit the horizontal bounds by default.
    ========================================
    //code for image starts
            BufferedImage myPicture;
            JLabel picLabel = null;
            try {
                 myPicture = ImageIO.read(new File("artes_header.png"));
                    picLabel = new JLabel(new ImageIcon(myPicture));
              } catch (Exception e) {
            GridBagLayout gLayout = new GridBagLayout();
            getContentPane().setLayout(gLayout);
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 1;
            c.weightx = 1;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(0, 0, 0, 0);
            panelTop.setBackground(Color.white);
            getContentPane().add(picLabel, c);
            c.gridx = 1;
            c.gridy = 2;
            c.weightx = 1;
            c.weighty = 1;
            getContentPane().add(tabPane, c);========================================
    Kindly anyone help me solve the same issue.
    Many thanks in advance.
    Regards,
    Gaurav
    Edited by: user7668872 on Jul 31, 2011 6:25 AM
    Edited by: user7668872 on Aug 4, 2011 3:56 AM

    Your questions doesnt make a whole lot of sence so not sure if this is what you want...
    This is a class to display an image on a jpanel. You can then use layout managers to make sure it is centrally alligned
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.*;
    class testImagePanel{
        public static void main(String[] args){
            BufferedImage image = null;
            ImagePanel imagePanel = null;
            try{
                image = ImageIO.read(new File("image.jpg"));
                imagePanel = new ImagePanel(image);
                imagePanel.setLayout(new BorderLayout());
            }catch(IOException  e){
                 System.err.println("Error trying to read in image "+e);
            JFrame frame = new JFrame("Example");
            frame.add(imagePanel);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);               
    public class ImagePanel extends JPanel {
        private BufferedImage image;
        private Dimension size;
        public ImagePanel(BufferedImage image) {
            this.image = image;
            this.size = new Dimension();
            size.setSize(image.getWidth(), image.getHeight());
            this.setBackground(Color.WHITE);
        @Override
        protected void paintComponent(Graphics g) {
            // Center image in this component.
            int x = (getWidth() - size.width)/2;
            int y = (getHeight() - size.height)/2;
            g.drawImage(image, x, y, this);
        @Override
        public Dimension getPreferredSize() { return size; }
    }

  • Image resizing & conerting to byte[]

    I'm working on a servlet. I have an image stored in a database
    (jpg or gif), and i need to resize it before sending to browser.
    I know how to create an Image from a byte array, and resize it,
    but how can i create again a gif/jpg file from the Image object
    and transform it again to a byte array to send to client?
    Thanks!!

    Hm...that was only half the answer...
    For jpg encoders, there is one in rt.jar that works, but it requires some manual labor...and starting up the awt event thread which is sort of costly.
    Here's an example of how to encode a file to jpg.
    (You must include rt.jar in the classpath for it to compile and run)
    import com.sun.image.codec.jpeg.*;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    public class Test extends JFrame
         public Test()
              super("JPG encoder");
              getContentPane().setLayout(new GridLayout(2,1));
              ImageIcon theIcon = new ImageIcon("image.gif");
              int w = theIcon.getIconWidth();
              int h = theIcon.getIconHeight();
              getContentPane().add(new JLabel(theIcon));
              setVisible(true);
              BufferedImage theImage = (BufferedImage)createImage(w, h);
              theImage.createGraphics().drawImage(theIcon.getImage(), 0, 0, Color.black,null);
              setLocation(300,300);
              try
                   FileOutputStream theStream = new FileOutputStream("image.jpg");
                   JPEGImageEncoder theEncoder = JPEGCodec.createJPEGEncoder(theStream);
                   theEncoder.encode(theImage);
                   ImageIcon theNewIcon = new ImageIcon("image.jpg");
                   getContentPane().add(new JLabel(theNewIcon));
                   pack();
              catch (Exception e)
              {e.printStackTrace();}
         public static void main(String[] args)
              new Test();
    }You can easily change that FileOutputStream to a ByteArrayOutputStream and then just extract the bytes...

  • Useless code in java.awt.image.SampleModel.java?

    Hey there,
    i just looked up the sourcecode of java.awt.image.SampleModel.java in JDK 6
    I discovered two issues i'd like to discuss.
    1) on lines 736 to 739 this code is stated:
    if (iArray != null)
    pixels = iArray;
    else
    pixels = new int[numBands * w * h];
    I asked myself, why does this code exist? while the getPixels() method is overwritten twice by double[] getPixels() and float[] getPixels, it is impossible to reach the part of the java code that initializes the pixels-array. One could only step into that line if "null" is given for the i/d/fArray-parameter. but if one would do so, the Java parser couldn't determine, which method is to use. so this part of code is just useless IMHO.
    the java developers could get a little more performance out of this method if the if statement would be cut out - especially when reading a lot of very small rasters
    or, on the other hand, they could replace this piece of code by an explicit bounds check.
    When somebody touches this code, i would appreciate it if the errormessage "index out of bounds!" could be rewritten to be a little more verbose, like: Index out of bounds(x=123; y=456, maxX=100, maxY=400)!(numbers are just examples)
    I hope i didn't miss something very basic and could help improving this class a little bit.
    2) the local variable Offset(line 734) is coded against code conventions which say, variables shall start with a lowercase letter. Offset obviously doesn't fit that convention.
    best regards
    kdot

    One could only step into that line if "null" is given for the i/d/fArray-parameter. but if one would do so, the Java parser couldn't determine, which method is to use. so this part of code is just useless IMHO. You can have
    sampleModel.getPixels(x,y,w,h,(int[]) null, dataBuffer);No ambiguity on which method to use.
    the local variable Offset(line 734) is coded against code conventions which say, variables shall start with a lowercase letter. Offset obviously doesn't fit that convention. You're correct, offset is against coding conventions. So are many other examples scattered throughout the jdk source code. For example, Hashtable should be called HashTable. In some cases the coding conventions might not have been established when the original code was written. In other cases it might have been human error. In yet other cases the conventions were probably ignored. The person who wrote the SampleModel class did so some 10+ years ago (Java 1.2). Who knows what he/she was thinking at the time, and in all honesty - does it really matter in this case?
    Did you know there are some classes that declare unused local variables (ahem ColorConvertOp)? Some also have unused imports ( *** cough *** BufferedImage *** cough *** ). In essence, the jdk source code is not the epidemy of code correctness. But it's still pretty good.

  • OutOfMemory error in java.awt.image.DataBufferInt. init

    We have an applet application that performs Print Preview of the images in the canvas. The images are like a network of entities (it has pictures of the entities involve (let's say Person) and how it links to other entities). We are using IE to launch the applet.
    We set min heap space to 128MB, JVM max heap space to 256MB, java plugin max heap space to 256MB using the Control Panel > Java.
    When the canvas width is about 54860 and height is 1644 and perform Print Preview, it thows an OutOfMemoryError in java.awt.image.DataBufferInt.<int>, hence, the Print Preview page is not shown. The complete stack trace (and logs) is as follows:
    Width: 54860 H: 1644
    Max heap: 254 # using Runtime.getRuntime().maxMemory()
    javaplugin.maxHeapSize: 256M # using System.getProperties("javaplugin.maxHeapSize")
    n page x n page : 1x1
    Exception in thread "AWT-EventQueue-2" java.lang.OutOfMemoryError: Java heap space
         at java.awt.image.DataBufferInt.<init>(Unknown Source)
         at java.awt.image.Raster.createPackedRaster(Unknown Source)
         at java.awt.image.DirectColorModel.createCompatibleWritableRaster(Unknown Source)
         at java.awt.image.BufferedImage.<init>(Unknown Source)
         at com.azeus.gdi.chart.GDIChart.preparePreview(GDIChart.java:731)
         at com.azeus.gdi.chart.GDIChart.getPreview(GDIChart.java:893)
         at com.azeus.gdi.ui.GDIUserInterface.printPreviewOp(GDIUserInterface.java:1526)
         at com.azeus.gdi.ui.GDIUserInterface$21.actionPerformed(GDIUserInterface.java:1438)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Drilling down the cause of the problem. The OutOfMemory occurred in the constructor of DataBufferInt when it tried to create an int array:
    public DataBufferInt(int size) {
    super(STABLE, TYPE_INT, size);
    data = new int[size]; # this part produce out of memory error when size = width X height
    bankdata = new int[1][];
    bankdata[0] = data;
    The OutOfMemory error occurred when size is width * height (54860 X 1644) which is 90,189,840 bytes (~86MB).
    I can replicate the OutOfMemory error when initiating an int array using a test class when it uses the default max heap space but if I increase the heap space to 256MB, it cannot be replicated in the test class.
    Using a smaller width and height with product not exceeding 64MB, the applet can perform Print Preview successfully.
    Given this, I think the java applet is not using the value assigned in javaplugin.maxHeapSize to set the max heap space, hence, it still uses the default max heap size and throws OutOfMemory in int array when size exceeds the default max heap space which is 64MB.
    For additional information, below is some of the java properties (when press S in java applet console):
    browser = sun.plugin
    browser.vendor = Sun Microsystems, Inc.
    browser.version = 1.1
    java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
    java.awt.printerjob = sun.awt.windows.WPrinterJob
    java.class.path = C:\PROGRA~1\Java\jre6\classes
    java.class.version = 50.0
    java.class.version.applet = true
    java.runtime.name = Java(TM) SE Runtime Environment
    java.runtime.version = 1.6.0_17-b04
    java.specification.version = 1.6
    java.vendor.applet = true
    java.version = 1.6.0_17
    java.version.applet = true
    javaplugin.maxHeapSpace = 256M
    javaplugin.nodotversion = 160_17
    javaplugin.version = 1.6.0_17
    javaplugin.vm.options = -Xms128M -Djavaplugin.maxHeapSpace=256M -Xmx256m -Xms128M
    javawebstart.version = javaws-1.6.0_17
    Kindly advise if this is a bug in JRE or wrong setting. If wrong setting, please advise on the proper way to set the heap space to prevent OutOfMemory in initializing int array.
    Thanks a lot.
    Edited by: rei_xanther on Jun 28, 2010 12:01 AM
    Edited by: rei_xanther on Jun 28, 2010 12:37 AM

    rei_xanther wrote:
    ..But the maximum value of the int data type is 2,147,483,647. That is the maximum positive integer value that can be stored in (the 4 bytes of) a signed int, but..
    ..The value that I passed in the int array size is only 90,189,840...its only connection with RAM is that each int requires 4 bytes of memory to hold it.
    new int[size] -- size is 90,189,840Sure. So the number of bytes required to hold those 90,189,840 ints is 360,759,360.
    I assumed that one element in the int array is 1 byte. ..Your assumption is wrong. How could it be possible to store 32 bits (4 bytes) in 8 bits (1 byte)? (a)
    a) Short of some clever compression algorithm applied to the data.

  • How can I create a java.awt.Image from ...

    Hi all,
    How can I create a java.awt.Image from a drawing on a JPanel?
    Thanks.

    JPanel p;
    BufferedImage image =
        new BufferedImage(p.getWidth(), p.getHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = image.createGraphics();
    p.paint(g);
    g.dispose();

Maybe you are looking for

  • Logic pro 9.1.6 (1700.43) crashes all the time under lion with mac mini server

    Hi, I run logic pro 9 with a mac mini server under lion 10.7.2 and it crashes all the time I get this crash report: Anyone knows how to solve this? Thanks Process:         Logic Pro [1877] Path:            /Applications/Logic Pro.app/Contents/MacOS/L

  • Can i use this cheap telly with apple tv?

    hi all - i was about to buy a soundbridge music streamer - mainly to play itunes through my hifi but for the extra £50 i am now thinking about an apple tv but i lack the approprite telly - i am about to buy one for the bedroom so would the one listed

  • IPhone as a computer replacement

    A friend of mine is considering purchasing an iPhone. Her desire is to use the iPhone as her only phone AND as a replacement to her computer. Is anyone out there doing anything similar? If so, could you please offer me suggestions, cautions, limitati

  • XL Reporter Run time error.

    Hi Experts, while changing the row level into colum level in XL Reporter (Composer)there is an error occuring that is called as ' Run time Error ' then its become hanged.. For examble in Parameter: Purchase order,GRPO , AP-Invoice. based on this am c

  • Diff between OEL AND RHEL

    Hi, Can someone please help me to understand differences between Oracle Enterprise Linux 5 and RHEL 5 or some sort of comparision. I know some people prefer Oracle Enterprise Linux for Development/UAT environment and RHEL for Production. Assume if bo