参考
使用Java缩放图片的工具:填充背景颜色,设置压缩比例,设置生成图片大小的比例
- 设置背景图片,使用setPaint()方法
1 2 3 4 |
Graphics2D g = resizedImage.createGraphics(); g.setPaint(this.bgcolor); g.fillRect(0, 0, targetWidth, targetHeight); this.hasDrawBgColor = true; |
- 设置压缩比例
1 2 3 4 5 6 7 |
ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(fileExtension) .next(); ImageWriteParam imgWriteParam = imgWriter.getDefaultWriteParam(); if (imgWriteParam.canWriteCompressed()) { imgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imgWriteParam.setCompressionQuality(this.quality); } |
- 设置生成图片大小的比例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
/** * 重新设置图片大小 * @param srcImage * @return */ private BufferedImage resize(BufferedImage srcImage) { int width = srcImage.getWidth(); int height = srcImage.getHeight(); if (this.width > 0 && this.height > 0) { if (this.fixedGivenSize) { this.givenWidth = this.width; this.givenHeight = this.height; if (!this.keepRatio) { width = this.width; height = this.height; } } if (this.keepRatio) { int drawWidth = this.width; int drawHeight = this.height; double sourceRatio = (double) width / (double) height; double targetRatio = (double) this.width / (double) this.height; if (Double.compare(sourceRatio, targetRatio) != 0) { if (sourceRatio > targetRatio) { drawHeight = (int) Math.round(this.width / sourceRatio); } else { drawWidth = (int) Math.round(this.height * sourceRatio); } } if (!this.fixedGivenSize) { this.givenWidth = drawWidth; this.givenHeight = drawHeight; } width = drawWidth; height = drawHeight; } } else if (this.scale > 0) { width = (int)(width * this.scale); height = (int)(height * this.scale); } else if (this.width > 0 && this.height == 0) { height = this.width * height / width; width = this.width; } else if (this.width == 0 && this.height > 0) { width = this.height * width / height; height = this.height; } if (width <= 1 || height <= 1) { throw new IllegalStateException("width or height value error!"); } this.width = width; this.height = height; this.givenWidth = (this.givenWidth == 0 ? width : this.givenWidth); this.givenHeight = (this.givenHeight == 0 ? height : this.givenHeight); return this.createImage(srcImage, width, height); } |
调用:
1 2 3 4 5 6 7 8 9 10 11 12 |
String str = ImageUtilsTest.class.getResource("/org.jpg").getPath(); File f = new File(str); //原图片 ImageUtils.fromFile(f) //设置原图片 //.width(200) //设置生成图片的宽度,高度将以原图片的高度等比例伸缩 //.height(200) //设置生成图片的高度,宽度将以原图片的宽度等比例伸缩 //.scale(1) //设置生成图片的伸缩比例 //.size(200, 22) //设置生成图片的宽度和高度 .rotate(34) //设置原图片的旋转角度 .bgcolor(Color.BLUE) //设置背景颜色,设置成null表示不处理背景颜色 .quality(0.6 f) //设置压缩比例 .toFile(new File("d:\\image\\test.jpg")); //生成图片的路径 |
原图片为:
输出的图片如下:
下载:前往下载
演示:Demo
ResizeImage.getExtension(targetFile);
这个方法没有
更新了
不错哟
能否用白色或者透明填充呢
可以
bgcolor(null)
不过暂时只能对png的图片有效