Solved

Resizing an image in java.

Posted on 2004-04-22
55
1,237 Views
Last Modified: 2007-12-19
Hi,

Im wondering is it posible to resize an image in java,say at the moment in a section of website im working on im blending 2 images, which works perfect aslong as both images are in set sizes. Im wondering if theres a way to re-size an image ,say i want all images to be 200*300 regardless of they're original size without losing any of the original image contents...


Thanks in advance,
Triggered


0
Comment
Question by:Triggered
  • 19
  • 15
  • 7
  • +4
55 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 10888949
Yes just scale the graphics

Graphics2D g2d = (Graphics2D)g;
g.scale(0.5f, 0.5f);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10888961
>>g.scale(0.5f, 0.5f);

should have been

g2d.scale(0.5, 0.5);
// then save as new image
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10889169
If you're displaying the image in a JLabel maybe this code can help you:

private void updatePicture(ImageIcon imageIcon) {
        if (imageIcon==null) return;
        Image img = imageIcon.getImage();
        Dimension d = getScaledSize(imageIcon);
        JLabel imageLbl = new JLabel( new ImageIcon(
            img.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH) ) );
        imageLbl.setBounds(0, 0, d.width, d.height);
        imagePanel.removeAll();
        imagePanel.add(imageLbl);
        imagePanel.revalidate();
        imagePanel.repaint();
}

private Dimension getScaledSize(ImageIcon image) {
        double imageRatio =
            (double)image.getIconWidth() / (double)image.getIconHeight();
       
        if ( imageRatio > 1.0)
            return new Dimension( MAX_IMG_WIDTH,
                                  (int)(((double)MAX_IMG_HEIGHT)/imageRatio) );
        else
            return new Dimension( (int)(((double)MAX_IMG_WIDTH)*imageRatio),
                                  MAX_IMG_HEIGHT );
}


In your case:

        Image img = imageIcon.getImage();
        Dimension d = new Dimension(200, 300);  // <<<<<<<<<<<<<<<<<<<<
        JLabel imageLbl = new JLabel( new ImageIcon(
            img.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH) ) );
        imageLbl.setBounds(0, 0, d.width, d.height);
        imagePanel.removeAll();
        imagePanel.add(imageLbl);
        imagePanel.revalidate();
        imagePanel.repaint();
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10889283
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 10889322
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10889396
>>are you still cross with me ...

Of course not! I was just rather hoping that you'd know that Swing components are not meant, strictly speaking, to be updated from application threads, as opposed to the EDT, which is precisely what's going on here. But we'd better not digress... ;-)

0
 

Author Comment

by:Triggered
ID: 10889469
say at the moment i have

say
IMAGE_WIDTH =200,IMAGE_HEIGTH=300

    BufferedImage readImage1 = new BufferedImage(IMAGE_WIDTH,IMAGE_HEIGTH,BufferedImage.TYPE_INT_ARGB);
                         readImage1 = ImageIO.read(new File(sourceName1));


which takes in an image but it only takes in small bit of the image if the the image inidicated by sourceName1 is a large image say 800*600

Ho do i overcome this
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10889503
>>Ho do i overcome this

But presumably that's why you want to scale it? If the image is bigger, you have to read it at its correct size first

BufferedImage readImage1 = ImageIO.read(new File(sourceName1));
0
 

Author Comment

by:Triggered
ID: 10889521
Sorry I worded that wrong CEHJ, I meant to say how do i resize  readImage1  once i have the whole image read in
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10889538
Image image = new ImageIcon("image.gif").getImage();
Image scaledImg = new ImageIcon(imgage.getScaledInstance(200, 300, Image.SCALE_SMOOTH) ) ).getImage();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10889650
>>I meant to say how do i resize  readImage1  

It depends on your 'rules'. If you decide in advance if you want a final image of 200 x 300, unless your source image happens to have an spect ration of 2/3 it's going to get distorted.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10889662
Typos:

>>have an spect ration

should have been

have an aspect ratio  
0
 

Author Comment

by:Triggered
ID: 10889829
I tried that zzynx but it didnt work

i have

Image image = new ImageIcon(sourceName1).getImage();
Image scaledImg = new ImageIcon(image.getScaledInstance(200, 300, Image.SCALE_SMOOTH) ).getImage();

where sourceName1 is the absoulute path of the image ie "c:\images\img.jpg" etc
0
 

Author Comment

by:Triggered
ID: 10889931
I'll get away with the image being disorted but  i need it at a fixed size since im blending it with another image
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10889971
>> I tried that zzynx but it didnt work
What do you get? What's the result?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10889997
Shouldn't that be "c:\\images\\img.jpg"? Don't remember...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10890081
BufferedImage readImage1 = new BufferedImage(IMAGE_WIDTH,IMAGE_HEIGHT,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D)readImage1.getGraphics();
int oW = origImage.getWidth(null);
int oH = origImage.getHeigth(null);
readImage1.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGHT);
g2d.drawImage(origImage, 0, 0, null);
g2d.dispose();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10890100
Sorry

>>readImage1.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGHT);

should be

g2d.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGHT);
0
 

Author Comment

by:Triggered
ID: 10890343
I tried that CEHJ
 but i doesnt seem to be resizing the image
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10890389
You *are* displaying 'readImage1' are you - rather than 'origImage'?
0
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10890522
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10890566
Test it first by saving to file:

g2d.drawImage(origImage, 0, 0, null);
ImageIO.write(readImage1, "JPG", new FileOutputStream("scaled.jpg"));
g2d.dispose();
0
 

Author Comment

by:Triggered
ID: 10890717
does it make a differnce if my images are in PNG format
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10890785
Not to whether they're scaled, no. What do you get when you save to file as i mentioned?
0
 

Author Comment

by:Triggered
ID: 10891327
g2d.drawImage(origImage, 0, 0, null);
ImageIO.write(readImage1, "JPG", new FileOutputStream("scaled.jpg"));

seems to work but the image is'nt scaled down
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10891405
Try

g2d.scale(IMAGE_WIDTH / oW, IMAGE_HEIGHT / oH);
0
 

Author Comment

by:Triggered
ID: 10891468
no i get the error message

"java.awt.image.ImagingOpException: Unable to invert transform AffineTransform[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]"

when i try that
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 86

Expert Comment

by:CEHJ
ID: 10891495
OK. Please post the exact code you're trying (before that little test ;-))
0
 

Author Comment

by:Triggered
ID: 10891525

IMAGE_WIDTH =200,IMAGE_HEIGTH=300

 Graphics2D g2d = (Graphics2D)readImage1.getGraphics();
 int oW = readImage1.getWidth();
 int oH = readImage1.getHeight();
      g2d.scale(oW/IMAGE_WIDTH , oW/IMAGE_HEIGTH );
      g2d.drawImage(readImage1, 0, 0, null);
      ImageIO.write(readImage1, "PNG", new FileOutputStream("scaled.png"));


....."scaled.png"  is a copy of the original image
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10891570
>>int oW = readImage1.getWidth();

should be

int oW = origImage.getWidth();

and the same for the height
0
 

Author Comment

by:Triggered
ID: 10891675
BufferedImage readImage1 = ImageIO.read(new File(sourceName1));
               


                  Graphics2D g2d = (Graphics2D)readImage1.getGraphics();
              int oW = readImage1.getWidth();
              int oH = readImage1.getHeight();
                 g2d.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGTH);
                  g2d.drawImage(readImage1, 0, 0, null);
                  ImageIO.write(readImage1, "PNG", new FileOutputStream("scaled.png"));



.....i thought readImage1  is my origImage ????
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10891723
>>.....i thought readImage1  is my origImage ????

No - i didn't intend it to be. Let's call the two 'origImage' and 'scaledImage':


BufferedImage scaledImage = new BufferedImage(IMAGE_WIDTH,IMAGE_HEIGHT,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D)scaledImage.getGraphics();
int oW = origImage.getWidth(null);
int oH = origImage.getHeigth(null);
g2d.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGHT);
g2d.drawImage(origImage, 0, 0, null);
g2d.dispose();

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10891738
iow, origImage is the original image you want to scale and scaledImage is the image you create
0
 

Author Comment

by:Triggered
ID: 10891792
im confused as to where your getting "origImage" as

im using :-

readImage1 = ImageIO.read(new File(sourceName1));


where sourcname is the filepath of the image i want to scale
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10891838
OK. Use the code i just posted and do a find replace. Replace 'origImage' by 'readImage1'
0
 

Author Comment

by:Triggered
ID: 10891945
i think i know what u doing now..

heres what i have but "scaled.png" is still only a copy of the original as opposed to being 200*300 in szie



                   BufferedImage readImage1 = ImageIO.read(new File(sourceName1));
                  BufferedImage scaledImage = new BufferedImage(IMAGE_WIDTH,IMAGE_HEIGTH,BufferedImage.TYPE_INT_ARGB);
                  Graphics2D g2d = (Graphics2D)scaledImage.getGraphics();
                  int oW = readImage1.getWidth();
                  int oH = readImage1.getHeight();
                  g2d.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGTH);
                  g2d.drawImage(readImage1, 0, 0, null);

                  ImageIO.write(readImage1, "PNG", new FileOutputStream("scaled.png"));
                  g2d.dispose();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10892174
>>ImageIO.write(readImage1, "PNG", new FileOutputStream("scaled.png"));

You're writing the original instead of the scaled one
0
 

Author Comment

by:Triggered
ID: 10892883
what should it be ?
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10893790
Maybe all you need to do is to mess around with this :

 Image getScaledInstance(int width, int height, int hints)  

which works for small thumbnails, so should work elsewhere, I trust.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10893806
That's probably a good idea!
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10893863
:) - lol!
0
 
LVL 92

Expert Comment

by:objects
ID: 10894341
> Maybe all you need to do is to mess around with this :
> Image getScaledInstance(int width, int height, int hints)  

if you're going to join a thread late its a good idea to read the previous posts :)

0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 10894377
heres some sample code that creates a thumbnail of an image, you should be able to adapt it to your purpose:

File thumb = new File(file.getParentFile(), file.getName()+".thumb");
Image i = new ImageIcon(file.getCanonicalPath()).getImage();
int w = i.getWidth(null);
int h = i.getHeight(null);
double ratio = (double) W / (double) w;
AffineTransform scale = AffineTransform.getScaleInstance(ratio, ratio);
BufferedImage scaled = new BufferedImage(W, (int)(h*ratio), BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.setTransform(scale);
g.drawImage(i, 0, 0, null);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(thumb));
JPEGEncodeParam jpegParams = encoder.getDefaultJPEGEncodeParam(scaled);
jpegParams.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(jpegParams);
encoder.encode(scaled);
0
 
LVL 92

Expert Comment

by:objects
ID: 10894381
W is the desired width of the thumb, and it preservers the aspect ratio.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10894390
>> if you're going to join a thread late its a good idea to read the previous posts :)

If you are going to speak to me, you need an appointment! LOL.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10894402
>> If you are going to post comments, why can't they be in English? :P
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10897485
>> Maybe all you need to do is to mess around with this :
>> Image getScaledInstance(int width, int height, int hints)
That's what I mentioned in my first comment, yes.

>> I tried that zzynx but it didnt work
to Triggered:
Again: What do you get? What's the result?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10897526
This works perfectly for me:

Image image = new ImageIcon("c:\\images\\img.jpg").getImage();
Image scaledImg = new ImageIcon(image.getScaledInstance(200, 300, Image.SCALE_SMOOTH) ).getImage();
jPanel1.add(new JLabel(new ImageIcon(scaledImg)));

Did you read my comment:
>> Shouldn't that be "c:\\images\\img.jpg"?
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10897752
I thought this was a discussion forum, not Guantanamo Bay.
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 10897755
Goodbye.
0
 

Author Comment

by:Triggered
ID: 10907061
Thanks for the help guys,
Sorry for not not getting back sooner, the thumbnail idea is great objects
0
 
LVL 92

Expert Comment

by:objects
ID: 10909629
:)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10916588
Disappointed you never answered my question
0
 

Author Comment

by:Triggered
ID: 10964146
Read the post again there zzynx and your right both the path i was using...sorry for not replying sooner
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mapAB Challlenge 35 85
unix in java example 9 40
compre toata in where clue oracle 4 41
Java Jpanels and Jframe 8 20
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now