Skip to content

Instantly share code, notes, and snippets.

@tresbailey
Created May 12, 2015 20:58
Show Gist options
  • Save tresbailey/3bcb228446f4fd85d2be to your computer and use it in GitHub Desktop.
Save tresbailey/3bcb228446f4fd85d2be to your computer and use it in GitHub Desktop.
Image Resize in Java
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.imageio.ImageIO;
public class ImageManipulationService {
public byte[] generateDimensionedImage(int targetWidth, int targetHeight, BufferedImage imageData) throws InvalidRepresentationException, ConflictingResourceException {
BufferedImage resizedImage = null;
try {
resizedImage = new BufferedImage(targetWidth, targetHeight, imageData.getType());
} catch(IllegalArgumentException except) {
throw new ConflictingResourceException("File Constraints are not valid. Dimensions must be valid: "+ except.getLocalizedMessage());
}
Graphics2D g = resizedImage.createGraphics();
g.drawImage(imageData, 0, 0, targetWidth, targetHeight, null);
g.dispose();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream())
{
ImageIO.write( resizedImage, "png", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
return imageInByte;
} catch (IOException except) {
except.printStackTrace();
throw new InvalidRepresentationException("The image to resize was not valid, and thus could not be resized: " + except.getLocalizedMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment