Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1333
  • Last Modified:

Resizing an image in java.

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
Triggered
Asked:
Triggered
  • 19
  • 15
  • 7
  • +4
1 Solution
 
CEHJCommented:
Yes just scale the graphics

Graphics2D g2d = (Graphics2D)g;
g.scale(0.5f, 0.5f);
0
 
CEHJCommented:
>>g.scale(0.5f, 0.5f);

should have been

g2d.scale(0.5, 0.5);
// then save as new image
0
 
zzynxSoftware engineerCommented:
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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
CEHJCommented:
>>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
 
TriggeredAuthor Commented:
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
 
CEHJCommented:
>>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
 
TriggeredAuthor Commented:
Sorry I worded that wrong CEHJ, I meant to say how do i resize  readImage1  once i have the whole image read in
0
 
zzynxSoftware engineerCommented:
Image image = new ImageIcon("image.gif").getImage();
Image scaledImg = new ImageIcon(imgage.getScaledInstance(200, 300, Image.SCALE_SMOOTH) ) ).getImage();
0
 
CEHJCommented:
>>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
 
CEHJCommented:
Typos:

>>have an spect ration

should have been

have an aspect ratio  
0
 
TriggeredAuthor Commented:
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
 
TriggeredAuthor Commented:
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
 
zzynxSoftware engineerCommented:
>> I tried that zzynx but it didnt work
What do you get? What's the result?
0
 
zzynxSoftware engineerCommented:
Shouldn't that be "c:\\images\\img.jpg"? Don't remember...
0
 
CEHJCommented:
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
 
CEHJCommented:
Sorry

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

should be

g2d.scale(oW /IMAGE_WIDTH, oH / IMAGE_HEIGHT);
0
 
TriggeredAuthor Commented:
I tried that CEHJ
 but i doesnt seem to be resizing the image
0
 
CEHJCommented:
You *are* displaying 'readImage1' are you - rather than 'origImage'?
0
 
rama_krishna580Commented:
0
 
CEHJCommented:
Test it first by saving to file:

g2d.drawImage(origImage, 0, 0, null);
ImageIO.write(readImage1, "JPG", new FileOutputStream("scaled.jpg"));
g2d.dispose();
0
 
TriggeredAuthor Commented:
does it make a differnce if my images are in PNG format
0
 
CEHJCommented:
Not to whether they're scaled, no. What do you get when you save to file as i mentioned?
0
 
TriggeredAuthor Commented:
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
 
CEHJCommented:
Try

g2d.scale(IMAGE_WIDTH / oW, IMAGE_HEIGHT / oH);
0
 
TriggeredAuthor Commented:
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
 
CEHJCommented:
OK. Please post the exact code you're trying (before that little test ;-))
0
 
TriggeredAuthor Commented:

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
 
CEHJCommented:
>>int oW = readImage1.getWidth();

should be

int oW = origImage.getWidth();

and the same for the height
0
 
TriggeredAuthor Commented:
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
 
CEHJCommented:
>>.....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
 
CEHJCommented:
iow, origImage is the original image you want to scale and scaledImage is the image you create
0
 
TriggeredAuthor Commented:
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
 
CEHJCommented:
OK. Use the code i just posted and do a find replace. Replace 'origImage' by 'readImage1'
0
 
TriggeredAuthor Commented:
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
 
CEHJCommented:
>>ImageIO.write(readImage1, "PNG", new FileOutputStream("scaled.png"));

You're writing the original instead of the scaled one
0
 
TriggeredAuthor Commented:
what should it be ?
0
 
krakatoaCommented:
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
 
CEHJCommented:
That's probably a good idea!
0
 
krakatoaCommented:
:) - lol!
0
 
objectsCommented:
> 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
 
objectsCommented:
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
 
objectsCommented:
W is the desired width of the thumb, and it preservers the aspect ratio.
0
 
krakatoaCommented:
>> 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
 
krakatoaCommented:
>> If you are going to post comments, why can't they be in English? :P
0
 
zzynxSoftware engineerCommented:
>> 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
 
zzynxSoftware engineerCommented:
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
 
krakatoaCommented:
I thought this was a discussion forum, not Guantanamo Bay.
0
 
krakatoaCommented:
Goodbye.
0
 
TriggeredAuthor Commented:
Thanks for the help guys,
Sorry for not not getting back sooner, the thumbnail idea is great objects
0
 
objectsCommented:
:)
0
 
zzynxSoftware engineerCommented:
Disappointed you never answered my question
0
 
TriggeredAuthor Commented:
Read the post again there zzynx and your right both the path i was using...sorry for not replying sooner
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 19
  • 15
  • 7
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now