Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reading, Resizing, and Writing Images

Mike DeStefano
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been banging my head against the wall (literally) trying to figure out how to do something that should be very easy.
I want to reading in an image file - "logo.jpg".
I want to resize the width and height to 150%.
I want to write the resized image to "logoResized.jsp".
First thing I tried was to read the image file into a BufferedImage. I can scale it using the method getScaledInstance(). This gives me an Image instance. The problem here is I can't see a way of writing the image to a file. ImageWriter wants a to write a RenderedImage, which I no longer have.
I have tried using an ImageReadParam to setSourceRenderSize(dimension) but I get an Exception thrown back because every reader I get has canSetSourceRenderSize() == false.

Here's the code I'm currently using which doesn't work to read, resize, and write a resized image.
Has anyone had success altering and writing images?
String fileBase = "C:/images";
String src = "/logo.gif";
String fileTy = src.substring(src.lastIndexOf('.')+1);
File file = new File(fileBase + src);
ImageInputStream iis = ImageIO.createImageInputStream(file);
ImageReader reader = null;
ImageReadParam param = null;
//for (Iterator readers = ImageIO.getImageReaders(iis); readers.hasNext() {
for (Iterator readers = ImageIO.getImageReadersByFormatName(fileTy); readers.hasNext() {
reader = (ImageReader);
param = reader.getDefaultReadParam();
if (param.canSetSourceRenderSize()) {
int imageIndex = 0;
double widthMod = 1.5;
double heightMod = 1.5;
double baseWidth = 800;
double baseHeight = 600;
int picWidth = 181;
int picHeight = 78;
int outWidth = (int)(picWidth * widthMod + .5);
int outHeight = (int)(picHeight * heightMod + .5);

BufferedImage bi = null;
//Rectangle rect = new Rectangle(0, 0, outWidth, outHeight);
param.setSourceRenderSize(new Dimension(outWidth, outHeight));
reader.setInput(iis, true);
bi =, param);
System.out.println(bi.getWidth() + "x" + bi.getHeight());
//Image im = bi.getScaledInstance(outWidth, outHeight, BufferedImage.SCALE_DEFAULT);
File outFile = new File(fileBase + src.substring(0,src.lastIndexOf('.')) + "Resized." + fileTy);
ImageIO.write(bi, fileTy, outFile);
Chella Anu
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To write an Image in a File:
Create a Buffered Image and then use JPEGcodec to write the image to a file
BufferedImage BImgScale=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
java.awt.Graphics2D grap=BImgScale.createGraphics();
OutputStream out = new FileOutputStream("<imgname>.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic