views:

38

answers:

2

I'm having a problem, when I save my image I can't open it because it's empty and the size is zero kb. I'm reading the image from a folder and then I change the size to 100x100 and save it but it's not working. Here's the code I've written so far:

public BufferedImage resizeImageToPreview() {

 final String SOURCE ="/Library/glassfishv3/glassfishv3/glassfish/domains/domain1/eclipseApps/LaFamilyEar/LaFamily_war/temp";
  File source = new File(SOURCE);

  BufferedImage image = null;

  //Read images and convert them to BufferedImages
  for (File img : source.listFiles()) {
   try {

    image = ImageIO.read(img);

   } catch (IOException e) {
    e.printStackTrace();
   }
   //Get image width and height
   int w = image.getWidth();  
   int h = image.getHeight(); 

   //Change the width and height to the image to 100x100
//   BufferedImage dimg = new BufferedImage(100, 100, image.getType());  

   //Create graphics to be able to paint or change your image
   Graphics2D g = image.createGraphics();  

   g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
   g.drawImage(image, 0, 0, 100, 100, 0, 0, w, h, null);  
   g.dispose(); 

   String extension = ".jpg";
   File dest = new File("/Users/ernestodelgado/Kurs_Java/EjbWorkspace/LaFamily/WebContent/small/"+img.getName());
   try {

    ImageIO.write(image, extension, dest);

   } catch (IOException e) {
    e.printStackTrace();
   }

  }

  return image;
 }
+1  A: 

Try changing ..

String extension = ".jpg";

..to..

String extension = "jpg";

Obviously, add a "." to the file name at the relevant point.

If that does not work for you, try posting an SSCCE.

Andrew Thompson
wow it worked u da best ;-) thanks A LOT i'm posting the code in case someone is looking for the same answer thanks again, this forum is awesome.
erde1017
+1  A: 

Try this example:

public class MakeSmaller {
    public static void main(String... args) throws MalformedURLException,
    IOException {

        String url = "http://actionstalk.com/wp-content/uploads/2007/11/google_logo_3600x1500.jpg";
        BufferedImage orig = ImageIO.read(new URL(url));

        BufferedImage scaled = new BufferedImage(50, 50, orig.getType());

        Graphics2D g = (Graphics2D) scaled.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(orig, 0, 0, scaled.getWidth(), scaled.getHeight(), null);
        g.dispose();

        ImageIO.write(scaled, "jpg", new File("test.jpg"));
    }
}
dacwe
wow it worked u da best ;-) thanks A LOT i'm posting the code in case someone is looking for the same answer thanks again, this forum is awesome.
erde1017
No problem, if you liked the answer you should accept it by clicking the accept button next to it (the outlined 'v'). :)
dacwe