Java文件处理:Image 图片裁剪、缩放和水印

创建图片

import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CreateImage {

    public static void main(String[] args) throws IOException {
        List<String> strList = new ArrayList<>();
        for (int i = 1; i <= 4; i++) {
            strList.add("这是第" + i + "行");
        }
        createImage("E:\\123.png", strList, new Font("宋体", Font.BOLD, 30), 720, 720);
    }

    /**
     * 功能描述:
     * <生成文字图片>
     *
     * @param strList  1 Graphics不支持\n换行
     * @param font     2 文字属性
     * @param filePath 3 文件路径
     * @param width    4 图片宽度
     * @param height   5 图片高度
     * @return void
     * @author zhoulipu
     * @date 2019/8/3 13:51
     */
    private static void createImage(String filePath, List<String> strList, Font font, int width, int height) {
        File file = new File(filePath);
        try {
            String suffix = StringUtils.substringAfterLast(file.getName(), ".");
            checkSuffixValid(suffix);
            // 创建图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            Graphics graphics = image.getGraphics();
            graphics.setClip(0, 0, width, height);
            // 背景色
            graphics.setColor(Color.white);
            graphics.fillRect(0, 0, width, height);
            // 文字颜色
            graphics.setColor(Color.red);
            // 字体
            graphics.setFont(font);
            // 垂直居中居中
            Rectangle clip = graphics.getClipBounds();
            FontMetrics fm = graphics.getFontMetrics(font);
            int ascent = fm.getAscent();
            int descent = fm.getDescent();
            int y = (clip.height - (ascent + descent)) / 2 + ascent;
            if (strList != null) {
                // 判断行数是否为奇数
                int num;
                if (strList.size() % 2 == 1) {
                    num = (strList.size() - 1) / 2;
                } else {
                    num = strList.size() / 2;
                }
                int n = -num;
                for (int i = 0; i < strList.size(); i++) {
                    graphics.drawString(strList.get(i), 2 * font.getSize(), y + (font.getSize() * n));
                    n++;
                }
            }
            graphics.dispose();
            // 输出png图片
            ImageIO.write(image, suffix, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述:
     * <校验图片后缀是否正确>
     *
     * @param suffix 1 图片文件后缀
     * @return void
     * @author zhoulipu
     * @date 2019/8/3 14:30
     */
    public static void checkSuffixValid(String suffix) {
        // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
        // 考虑后缀是否符合大小写规范,这里不直接使用数组
        String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("[", "").replace("]", ",");
        // 类型和图片后缀全部小写,然后判断后缀是否合法
        if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase() + ",") < 0) {
            throw new RuntimeException("文件后缀不规范,无法操作image文件,后缀示例:" + types.substring(0, types.length() - 1));
        }
    }

}

图片裁剪

import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CroppingImage {

    public static void main(String[] args) {
        croppingImage("E:\\123.png", "_clip", 20, 180, 240, 240);
    }

    /**
     * 功能描述:
     * <图片裁剪>
     *
     * @param filePath 1 文件路径
     * @param sufixo   2 截图后文件名末尾区分
     * @param x        3 横坐标
     * @param y        4 纵坐标
     * @param width    5 裁剪后宽度
     * @param height   6 裁剪后高度
     * @return void
     * @author zhoulipu
     * @date 2019/8/3 14:19
     */
    private static void croppingImage(String filePath, String sufixo, int x, int y, int width, int height) {
        File file = new File(filePath);
        Rectangle rect = new Rectangle(x, y, width, height);
        FileInputStream fis = null;
        ImageInputStream iis = null;
        try {
            String suffix = StringUtils.substringAfterLast(file.getName(), ".");
            CreateImage.checkSuffixValid(suffix);
            fis = new FileInputStream(file);
            // 将FileInputStream 转换为ImageInputStream
            iis = ImageIO.createImageInputStream(fis);
            // 根据图片类型获取该种类型的ImageReader
            ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            param.setSourceRegion(rect);
            BufferedImage image = reader.read(0, param);
            // 获取抽象路径
            String path = file.getPath();
            // 判断目录是否存在
            if (!file.isDirectory()) {
                path = file.getParent();
            }
            // 判断路径最后是否是目录转换符
            if (!path.endsWith(File.separator)) {
                path = path + File.separator;
            }
            // 写入新文件
            String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
            ImageIO.write(image, suffix, new File(pathNew));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (iis != null) {
                    iis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

图片缩放

import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

public class ZoomImage {

    public static void main(String[] args) throws IOException {
        zoomImage("E:\\123.png", 180, 180, "_zoom", true);
    }

    /**
     * 功能描述:
     * <图片缩放>
     *
     * @param filePath   1 文件路径
     * @param w          2 缩放后宽度
     * @param h          3 缩放后高度
     * @param sufixo     4 截图后文件名末尾区分
     * @param proportion 5 是否继承原图片长宽比例
     * @return void
     * @author zhoulipu
     * @date 2019/8/3 14:41
     */
    private static void zoomImage(String filePath, int w, int h, String sufixo, boolean proportion) throws IOException {
        File file = new File(filePath);
        String suffix = StringUtils.substringAfterLast(file.getName(), ".");
        CreateImage.checkSuffixValid(suffix);
        BufferedImage img = ImageIO.read(file);
        if (proportion) {
            // 根据原图与要求的缩略图比例,找到最合适的缩略图比例
            int width = img.getWidth(null);
            int height = img.getHeight(null);
            if ((width * 1.0) / w < (height * 1.0) / h) {
                if (width > w) {
                    h = Integer.parseInt(new DecimalFormat("0").format(height * w / (width * 1.0)));
                }
            } else {
                if (height > h) {
                    w = Integer.parseInt(new DecimalFormat("0").format(width * h / (height * 1.0)));
                }
            }
        }
        System.out.println("修改后的图片:height=" + h + ", width=" + w);
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
        graphics.dispose();
        String path = file.getPath();
        String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
        ImageIO.write(image, suffix, new File(pathNew));
    }

}

图片水印

import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class WatermarkImage {

    public static void main(String[] args) throws IOException {
        markTextMark("E:\\123.jpg", "_watermark_txt", "@愚昧的取经人");
        markImgMark("E:\\123.jpg", "_watermark_img", "E:\\watermark.jpg");
    }

    /**
     * 功能描述:
     * <文字水印>
     *
     * @param filePath         1
     * @param sufixo           2
     * @param waterMarkContent 3
     * @return void
     * @author zhoulipu
     * @date 2019/8/29 11:08
     */
    private static void markTextMark(String filePath, String sufixo, String waterMarkContent) throws IOException {
        // 水印颜色
        Color color = new Color(180, 180, 180, 100);
        File file = new File(filePath);
        // 获取图片后缀
        String suffix = StringUtils.substringAfterLast(file.getName(), ".");
        CreateImage.checkSuffixValid(suffix);
        Image srcImg = ImageIO.read(file);
        int width = srcImg.getWidth(null);
        int height = srcImg.getHeight(null);
        int fontLength = (int) (width * 0.028);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        graphics.drawImage(srcImg, 0, 0, width, height, null);
        graphics.setColor(color);
        graphics.setFont(new Font("微软雅黑", Font.PLAIN, fontLength));
        // 设置水印的坐标
        int x = (int) (width * 0.962 - getWatermarkLength(waterMarkContent, graphics));
        // 水印坐标的x值
        int y = (int) (height * 0.962 - fontLength);
        // 加水印
        graphics.drawString(waterMarkContent, x, y);
        graphics.dispose();
        // 输出图片
        String path = file.getPath();
        String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
        ImageIO.write(image, suffix, new File(pathNew));
    }

    /**
     * 功能描述:
     * <图片水印>
     *
     * @param filePath     1
     * @param sufixo       2
     * @param watermarkUrl 3
     * @return void
     * @author zhoulipu
     * @date 2019/8/29 11:50
     */
    private static void markImgMark(String filePath, String sufixo, String watermarkUrl) throws IOException {
        File file = new File(filePath);
        // 获取图片后缀
        String suffix = StringUtils.substringAfterLast(file.getName(), ".");
        CreateImage.checkSuffixValid(suffix);
        Image img = ImageIO.read(file);
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        ImageIcon imgIcon = new ImageIcon(watermarkUrl);
        Image con = imgIcon.getImage();
        float clarity = 0.6f;//透明度
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, clarity));
        // 设置水印的坐标
        int x = (int) (width * 0.962 - imgIcon.getIconWidth());
        // 水印坐标的x值
        int y = (int) (height * 0.962 - imgIcon.getIconHeight());
        graphics.drawImage(con, x, y, null);//水印的位置
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        graphics.dispose();
        // 输出图片
        String path = file.getPath();
        String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
        ImageIO.write(image, suffix, new File(pathNew));
    }

    /**
     * 功能描述:
     * <获取文字水印长度>
     *
     * @param waterMarkContent 1
     * @param g                2
     * @return int
     * @author zhoulipu
     * @date 2019/8/29 11:50
     */
    private static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Java图片上传处理缩放功能,可以使用Java提供的ImageIO类和BufferedImage类。以下是一个简单的示例代码: ```java import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageUtils { public static void resizeImage(File inputImage, File outputImage, int maxWidth, int maxHeight) throws Exception { BufferedImage input = ImageIO.read(inputImage); int width = input.getWidth(); int height = input.getHeight(); double ratio = (double) width / height; if (width > maxWidth || height > maxHeight) { if (width > height) { width = maxWidth; height = (int) (maxWidth / ratio); } else { height = maxHeight; width = (int) (maxHeight * ratio); } } BufferedImage output = new BufferedImage(width, height, input.getType()); Graphics2D g2d = output.createGraphics(); g2d.drawImage(input, 0, 0, width, height, null); g2d.dispose(); ImageIO.write(output, "jpg", outputImage); } } ``` 这个示例代码中,resizeImage()方法接收一个输入图片文件、一个输出图片文件、最大宽度和最大高度,然后对输入图片进行缩放处理,使其宽度和高度都不超过指定的最大值。缩放后的图片会保存到输出图片文件中。 使用时,可以像这样调用: ```java File inputFile = new File("input.jpg"); File outputFile = new File("output.jpg"); ImageUtils.resizeImage(inputFile, outputFile, 800, 600); ``` 这个示例代码只是一个简单的缩放示例,实际应用中还需要考虑更多的因素,例如图片格式、质量、裁剪等。但是使用Java提供的ImageIO和BufferedImage类,实现图片缩放功能还是比较容易的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值