Java modify image size size image scaling (URL image and local image)

Method 1: Use Image.getScaledInstance

Use Image.getScaledInstance under the awt package of jdk to realize image scaling. The advantage is that there is no need to introduce a third-party jar, and the disadvantage is that it will be a little vague.

Tool class ImageUtils:

package utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageUtils {
    /**
     * 通过BufferedImage图片流调整图片大小
     */
    public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_AREA_AVERAGING);
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        outputImage.getGraphics().drawImage(resultingImage, 0, 0, null);
        return outputImage;
    }


    /**
     * BufferedImage图片流转byte[]数组
     */
    public static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }


    /**
     * byte[]数组转BufferedImage图片流
     */
    private static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
        ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}

test:

1. Get the picture through url and save it after resizing:

import utils.ImageUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;


public class Test {
    public static void main(String[] args) {
        try {
            //通过url获取BufferedImage图像缓冲区
            URL img = new URL("https://img1.360buyimg.com/image/jfs/t1/38591/20/3737/314695/5cc69c01E1838df09/dd6dce681bd23031.jpg");
            BufferedImage image = ImageIO.read(img);
            //获取图片的宽、高
            System.out.println("Width: " + image.getWidth());
            System.out.println("Height: " + image.getHeight());
            //调整图片大小为 400X400尺寸
            BufferedImage newImage = ImageUtils.resizeImage(image,400,400);
            //将缓冲区图片保存到 F:/test/pic1.jpg (文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
            ImageIO.write(newImage, "jpg", new File("F:/test/pic1.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. Resize and save by reading the image file:

import utils.ImageUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) {
        try {
            //读取原始图片
            BufferedImage image = ImageIO.read(new FileInputStream("F:/test/pic1.jpg"));
            System.out.println("Width: " + image.getWidth());
            System.out.println("Height: " + image.getHeight());
            //调整图片大小
            BufferedImage newImage = ImageUtils.resizeImage(image,200,200);
            //图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
            ImageIO.write(newImage, "jpg", new File("F:/test/pic2.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Resize and save the picture file of MultipartFile type:

 public JSONObject imageSizeAdjustment(MultipartFile file) {
        JSONObject result = new JSONObject();
        try {
               //从MultipartFile 中获取 byte[]
            byte[] bytes = file.getBytes();
            //byte[]转 InputStream 
            InputStream in = new ByteArrayInputStream(bytes);
            //读取图片输入流为 BufferedImage 
            BufferedImage image = ImageIO.read(in);
            System.out.println("Width: " + image.getWidth());
            System.out.println("Height: " + image.getHeight());
            //调整图片大小
            BufferedImage newImage = ImageUtils.resizeImage(image, 200, 200);
            //图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
            ImageIO.write(newImage, "jpg", new File("F:/test/pic2.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        result.put("code", 1);
        result.put("note", "成功");
        return result;
    }

Method 2: Use Thumbnailator

Thumbnailator is an open source image resizing library for Java that uses progressive bilinear scaling. It supports JPG, BMP, JPEG, WBMP, PNG and GIF.

Include it in our project by adding the following Maven dependency to our pom.xml:

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.11</version>
</dependency>

Tool class ThumbnailsUtils:

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ThumbnailsUtils{
    private static final Logger logger = LoggerFactory.getLogger(ThumbnailsUtils.class);

    /**
     * 通过BufferedImage图片流调整图片大小
     */
    public static BufferedImage resizeImageOne(BufferedImage originalImage, int targetWidth, int targetHeight) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Thumbnails.of(originalImage)
                .size(targetWidth, targetHeight)
                .outputFormat("JPEG")
                .outputQuality(1)
                .toOutputStream(outputStream);
        byte[] data = outputStream.toByteArray();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
        return ImageIO.read(inputStream);
    }
   
    /**
     * BufferedImage图片流转byte[]数组
     */
    public static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "jpg", out);
        } catch (IOException e) {
            logger.error("错误信息: ", e);
        }
        return out.toByteArray();
    }


    /**
     * byte[]数组转BufferedImage图片流
     */
    private static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
        ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            logger.error("错误信息: ", e);
        }
        return image;
    }
}

test:

It is basically the same as the above test, except that ImageUtils.resizeImage is replaced by ThumbnailsUtils.resizeImageOne.

  • Download and convert Url images directly to File without modifying the size

/**
 *  将Url转换为File
 * @param url 图片在线链接
 * @param pathUrl 下载到本地路径
 * @return
 * @throws Exception
 */
public static File urltoFile(String url,String pathUrl) throws Exception {
    HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
    httpUrl.connect();
    InputStream ins=httpUrl.getInputStream();

    // 获取文件后缀
    String prefix = url.substring(url.lastIndexOf("."));
    String fileUrl = pathUrl + UUIDUtil.get32UUID()+prefix;
    File file = new File(fileUrl);//System.getProperty("java.io.tmpdir")缓存
    if (file.exists()) {
        file.delete();//如果缓存中存在该文件就删除
    }
    OutputStream os = new FileOutputStream(file);
    int bytesRead;
    int len = 8192;
    byte[] buffer = new byte[len];
    while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
    os.close();
    ins.close();
    return file;
}

Guess you like

Origin blog.csdn.net/yyongsheng/article/details/129062841