Java修改图片大小尺寸图片缩放(URL图片和本地图片)

方式一:使用Image.getScaledInstance

使用jdk的awt包下的Image.getScaledInstance实现图片的缩放。好处是无需引入第三方jar,缺点是会稍微有点模糊。

工具类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;
    }
}

测试:

1.通过 url 获取图片并调整大小后保存:

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、通过读取图片文件调整大小再保存:

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、MultipartFile类型的图片文件调整大小再保存:

 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;
    }

方式二:使用Thumbnailator

Thumbnailator是Java的开源图像大小调整库,它使用渐进式双线性缩放。它支持JPG,BMP,JPEG,WBMP,PNG和GIF。

通过将以下Maven依赖项添加到我们的pom.xml中,将其包括在我们的项目中:

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

工具类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;
    }
}

测试:

和上面测试基本一样只不过 ImageUtils.resizeImage换成 ThumbnailsUtils.resizeImageOne即可。

  • 不修改尺寸直接将Url图片下载并转化为File

/**
 *  将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;
}

猜你喜欢

转载自blog.csdn.net/yyongsheng/article/details/129062841