在dev2dev看到有人发帖子问,就随手写了一个,贴到这里来以后找起来方便。
java 代码
- /**
- *
- * @param imageFilename 图片文件名
- * @param width 要缩放的宽度
- * @param height 要缩放的高度
- * @throws IOException
- */
- private static void resize(String imageFilename, int width, int height) throws IOException {
- File inputFile = new File(imageFilename);
- BufferedImage input = ImageIO.read(inputFile);
- BufferedImage output = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_RGB);
- Graphics2D g2d = output.createGraphics();
- g2d.setBackground(Color.WHITE);
- g2d.fillRect(0, 0, width, height);
- int oWidth = input.getWidth();
- int oHeight = input.getHeight();
- int dx = oWidth < width ? (width - oWidth) / 2 : 0;
- int dy = oHeight < height ? (height - oHeight) / 2 : 0;
- int dw = Math.min(oWidth, width);
- int dh = Math.min(oHeight, height);
- g2d.drawImage(input, dx, dy, dw, dh, null);
- File outputFile = new File(inputFile.getName().substring(0, inputFile.getName().lastIndexOf('.')) + "_thumbnail.jpg");
- ImageIO.write(output, "jpg", outputFile);
- }