WANG LH , Research & Development

Java图像处理

2021.05.31 22:05

开源库:

https://github.com/coobird/thumbnailator

版本依赖:

    dependencies {
        compile 'net.coobird:thumbnailator:0.4.8'
    }

Java示例代码

public static byte[] resize(InputStream inputStream) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    BufferedImage bufferedImage = ImageIO.read(inputStream);
    int width = bufferedImage.getWidth();
    int height = bufferedImage.getHeight();
    if (width > 200 && width < 1024 && height > 200 && height < 1024) {
      ImageIO.write(bufferedImage, "jpg", outputStream);
      return outputStream.toByteArray();
    }

    if (width < 200) {
      width = 200;
    }
    if (width > 1024) {
      width = 1024;
    }
    if (height < 200) {
      height = 200;
    }
    if (height > 1024) {
      height = 1024;
    }

    Thumbnails.of(bufferedImage).size(width, height).outputFormat("jpg").toOutputStream(outputStream);
    return outputStream.toByteArray();
  }