Skip to content

Instantly share code, notes, and snippets.

@kentyeh
Created January 14, 2020 06:47
Show Gist options
  • Save kentyeh/7f1a27f39bc3306ceec7e830857a12ed to your computer and use it in GitHub Desktop.
Save kentyeh/7f1a27f39bc3306ceec7e830857a12ed to your computer and use it in GitHub Desktop.
重新調整影像大小
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
public class ResizeImage {
public static void resize(BufferedImage bufferedImage, int maxEdge, OutputStream os) throws IOException {
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight();
double factor = w >= h && w > maxEdge ? maxEdge * 1.0 / w : h > maxEdge ? maxEdge * 1.0 / h : 1;
Image rescaled = bufferedImage.getScaledInstance(w > h ? 500 : Long.valueOf(Math.round(w * factor)).intValue(),
h > w ? 500 : Long.valueOf(Math.round(h * factor)).intValue(), Image.SCALE_AREA_AVERAGING);
bufferedImage = new BufferedImage(w > h ? 500 : Long.valueOf(Math.round(w * factor)).intValue(),
h > w ? 500 : Long.valueOf(Math.round(h * factor)).intValue(), BufferedImage.TYPE_INT_ARGB);
java.awt.Graphics2D g = bufferedImage.createGraphics();
g.drawImage(rescaled, 0, 0, null);
g.dispose();
ImageIO.write(bufferedImage, "png", os);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment