BufferedImage旋转图片后图像边缘出现红色线条如何解决
图片旋转后出现红色线条问题排查
根本原因
红色边框和图片旋转逻辑没有任何关系,是你在代码里主动画上去的。
查看rotateImageByDegrees方法的逻辑,在调用g2d.drawImage把旋转后的原图绘制到新画布之后,你写了这两行代码:
g2d.setColor(Color.RED); g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
这两行的作用是把画笔颜色设为红色,沿着新画布的最外圈画一个1像素宽的矩形轮廓,最终输出的图片自然会带上一圈红边。
关联代码
public class TestOrienationImg { public static void main(String[] args) throws IOException { BufferedImage bi = ImageIO.read(new File("D:\\IMG_7282.jpg")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "jpg", baos); baos = rotateImageByDegrees(baos.toByteArray(), 90); OutputStream outputStream = new FileOutputStream ("D:\\v1\\xxx.jpg"); baos.writeTo(outputStream); } public static ByteArrayOutputStream rotateImageByDegrees(byte[] image, double angle) throws IOException { InputStream inputstream = new ByteArrayInputStream(image); double rads = Math.toRadians(angle); double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads)); BufferedImage img = ImageIO.read(inputstream); int w = img.getWidth(); int h = img.getHeight(); int newWidth = (int) Math.floor(w * cos + h * sin); int newHeight = (int) Math.floor(h * cos + w * sin); int type = img.getType() == 0? BufferedImage.TYPE_INT_ARGB : img.getType(); BufferedImage rotated = new BufferedImage(newWidth, newHeight, type); Graphics2D g2d = rotated.createGraphics(); AffineTransform at = new AffineTransform(); at.translate((newWidth - w) / 2, (newHeight - h) / 2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int x = w / 2; int y = h / 2; at.rotate(rads, x, y); g2d.setTransform(at); g2d.drawImage(img, 0, 0, null); g2d.setColor(Color.RED); g2d.drawRect(0, 0, newWidth - 1, newHeight - 1); g2d.dispose(); ImageIO.write(rotated, "jpg",baos); return baos; } }
效果参考
- 原始图片:

- 旋转后带红边的图片(因大小限制做过压缩):

修复方案
直接删掉上面那两行画红色矩形的代码,重新运行导出的旋转图片就不会有红边了。
顺便提个代码优化点:main方法里你先把读入的BufferedImage转成JPG格式字节数组,再传给旋转方法重新读成BufferedImage,这一步是完全多余的IO操作,会平白增加性能损耗,直接把旋转方法的入参改成BufferedImage类型,省略中间的流转换步骤就行。
内容的提问来源于stack exchange,提问作者mobiw
相关产品推荐
相关产品推荐

