JAVA 图片切片

package com.nece001;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class TaobaoImageMain {

    public static void main(String[] args) {
        Options options = new Options();
        options.addOption(new Option("h", "help", false, "帮助文档"));
        options.addOption(new Option("w", "width", true, "输出的图片宽度,淘宝480-1500"));
        options.addOption(new Option("m", "max-height", true, "输出切片的最大高度,淘宝:2500"));
        options.addOption(new Option("i", "input", true, "源图片文件名或保存源文件的目录,支持格式: .jpg .jpeg .png"));
        options.addOption(new Option("o", "output", true, "结果保存目录,不指定则使用源文件所在目录"));
        options.addOption(new Option("q", "quality", true, "图片输出的质量0-100"));

        CommandLine cli = null;
        CommandLineParser cliParser = new DefaultParser();
        try {
            cli = cliParser.parse(options, args);
        } catch (ParseException ex) {
            System.err.println("非法参数:" + ex.getMessage());
        }

        //System.out.println(options);
        int w = 750;
        int h = 2500;
        int q = 100;
        String i = "";
        String o = "";

        if (cli != null) {
            if (cli.hasOption('h')) {
                for (Option opt : options.getOptions()) {
                    System.out.println("-" + opt.getOpt() + "\t" + opt.getLongOpt() + "\t" + opt.getDescription());
                }
            } else {

                if (cli.hasOption('w')) {
                    w = Integer.parseInt(cli.getOptionValue('w'));
                }

                if (cli.hasOption('m')) {
                    h = Integer.parseInt(cli.getOptionValue('m'));
                }

                if (cli.hasOption('i')) {
                    i = cli.getOptionValue('i');
                }

                if (cli.hasOption('o')) {
                    o = cli.getOptionValue('o');
                }

                if (cli.hasOption('q')) {
                    q = Integer.parseInt(cli.getOptionValue('q'));
                }

                if (i.equals("")) {
                    System.err.println("没有指定源图片文件");
                } else {
                    List<String> files = new ArrayList<>();
                    File file = new File(i);
                    if (o.equals("")) {
                        o = file.isDirectory() ? file.getPath() : file.getParent();
                    }

                    if (file.isDirectory()) {
                        for (File f : file.listFiles((File dir, String name) -> {
                            if (name.endsWith("jpg") || name.endsWith("jpeg") || name.endsWith("png")) {
                                return true;
                            }
                            return false;
                        })) {
                            files.add(f.getPath());
                        }
                    } else {
                        files.add(file.getPath());
                    }

                    ImageSlicer image = new ImageSlicer();
                    image.setWidth(w);
                    image.setHeight(h);
                    image.setQuality(q);
                    for (String p : files) {
                        System.out.println(p + " ...");

                        image.setOriginal(p);
                        image.setOutput(o);
                        image.process();
                    }
                    
                    System.out.println("done.");
                }
            }
        }
    }

}

class ImageSlicer {

    private int width;
    private int height;
    private int quality;
    private String original;
    private String output;

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public void setOriginal(String original) {
        this.original = original;
    }

    public void setOutput(String output) {
        this.output = output;
    }

    public void setQuality(int quality) {
        this.quality = quality;
    }

    public void process() {
        File file = new File(original);
        String oName = file.getName().substring(0, file.getName().indexOf("."));

        String path = output + File.separator + "output" + File.separator + oName;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            slice(file, path);
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }

    private void slice(File file, String path) throws FileNotFoundException, IOException {
        BufferedImage image = ImageIO.read(file);
        int ow = image.getWidth();
        int oh = image.getHeight();
        int nHeight = oh; // 目标图片高度

        BufferedImage target = image;
        if (ow > width) { // 图片缩略
            nHeight = oh * width / ow;
            target = new BufferedImage(width, nHeight, BufferedImage.TYPE_INT_RGB);
            target.getGraphics().drawImage(image.getScaledInstance(width, nHeight, image.SCALE_SMOOTH), 0, 0, null);

            // 输出查看缩略图
            //File oFile = new File(path + File.separator + "a.jpg");
            //ImageIO.write(target, "JPEG", oFile);
        } else {
            width = ow;
        }

        int count = (int) Math.ceil(nHeight / height);
        int start = 0;
        BufferedImage tmp;
        for (int i = 0; i <= count; i++) {
            File sFile = new File(path + File.separator + i + ".jpg");

            if (start + height > nHeight) {
                height = nHeight - start;
            }
            tmp = target.getSubimage(0, start, width, height);

            BufferedImage slice = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            slice.getGraphics().drawImage(tmp, 0, 0, null);
            //ImageIO.write(slice, "JPEG", sFile);
            saveJpeg(slice, sFile, quality / 100F);

            start += height + 1;
        }
    }

    private void saveJpeg(BufferedImage image, File dist, float quality) throws IOException {
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        jpgWriter.setOutput(ImageIO.createImageOutputStream(dist));

        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
        jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpgWriteParam.setCompressionQuality(quality);

        jpgWriter.write(null, new IIOImage(image, null, null), jpgWriteParam);
        jpgWriter.dispose();
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值