最近工作上用到图片旋转,所以来偏图片旋转的文章。其中碰到不少坑。
以下实现了旋转90度的倍数。方便我们了解旋转是怎么做的 ,如果要旋转任意角度,可以用Java自带的thumbnails(文章后面介绍)
import org.springframework.util.Base64Utils; import net.coobird.thumbnailator.Thumbnails; /** * 旋转图片 * @param old_img * @param degess 旋转度数 负数为逆时针 //如果宽高比大于1 不旋转 * @return * @throws IOException */ public static BufferedImage rotateImage(BufferedImage bi, String times ) { int width = bi.getWidth(); int height = bi.getHeight(); BufferedImage biFlip = null; try { int count = Integer.valueOf(times); if(count>=4){ count = count % 4; } if(count==0) return bi; if(count==1){ biFlip = new BufferedImage(height,width, bi.getType()); for(int i=0; i<width; i++){ for(int j=0; j<height; j++){ biFlip.setRGB(height-1-j, i, bi.getRGB(i, j));//顺时针旋转 //旋转公式 R*(x,y) = (-y,x) } } }else if(count==2){ //旋转180度 biFlip = new BufferedImage(width,height, bi.getType()); for(int i=0; i<width; i++){ for(int j=0; j<height; j++){ biFlip.setRGB(width-1-i, height-1-j, bi.getRGB(i, j));//顺时针旋转180 } } }else { //逆时针旋转90 == 旋转270度 biFlip = new BufferedImage(height,width, bi.getType()); for(int i=0; i<width; i++){ for(int j=0; j<height; j++){ biFlip.setRGB(j, width-1-i, bi.getRGB(i, j)); } } } } catch(Exception e){ e.printStackTrace(); return bi; }finally { } return biFlip; }图片转base64
public static String encodeToString(BufferedImage image) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, "jpg", bos); byte[] imageBytes = bos.toByteArray(); imageString = Base64Utils.encodeToString(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; }base64转图片
public static BufferedImage baseToBufferedImage(String base64Sign){ ByteArrayOutputStream os = new ByteArrayOutputStream(); BufferedImage img = null; byte[] buffer=null; BufferedImage bufferImg =null ; try { buffer = Base64Utils.decodeFromString(base64Sign); ByteArrayInputStream input = new ByteArrayInputStream(buffer); bufferImg = ImageIO.read(input); } catch (Exception e) { e.printStackTrace(); return null; } return bufferImg; }**
**
1 Thumbnails.of(images)
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>可以是BufferedImage File InputStream URL 等途径
**
** a 压缩图片(拉伸图片) 压缩图片(选择操作的大小) size()是按照原图一width为准等比例压缩。forceSize()是强制压缩,可能导致图片变形。 也可以用scale指定比例,第二个方法可以指定长款分别压缩多少倍,等于图片拉伸操作。
b 旋转图片 Thumbnails.of(“”).scale(1).rotate(10); 旋转度数按顺时针旋转,如果要逆时针,可以传入负数。必须先指定大小既scale或用size指定。 3**
** 可以作为输出的方式也挺多的 。 总结 : 不管哪种方式实现,还是要注意几个问题 1 是图片旋转后编码的时候用BASE64Decoder编码解码,而BASE64Decoder编码时默认每隔76个字符加一个换行,导致旋转后编码变的很大,并且有换行的编码在转图片的时候就有问题,用spring自带的工具org.springframework.util.Base64Utils编解码;。 2是对于空白图片,在转成BufferedImage时Java把透明背景设置成了黑色背景,可以在操作之前把图片设置成白色背景。
