欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现图片裁剪功能的示例详解

程序员文章站 2022-06-18 11:05:27
目录前言maven依赖代码验证一下前言本文提供将图片按照自定义尺寸进行裁剪的java工具类,一如既往的实用主义。maven依赖 ...

前言

本文提供将图片按照自定义尺寸进行裁剪的java工具类,一如既往的实用主义。

maven依赖

        <dependency>
            <groupid>com.google.guava</groupid>
            <artifactid>guava</artifactid>
            <version>30.1.1-jre</version>
        </dependency>
        <dependency>
            <groupid>org.bytedeco</groupid>
            <artifactid>javacv-platform</artifactid>
            <version>1.5.5</version>
        </dependency>
        <dependency>
            <groupid>cn.hutool</groupid>
            <artifactid>hutool-all</artifactid>
            <version>5.5.2</version>
        </dependency>

代码

不废话,上代码。

package ai.guiji.csdn.tool;

import cn.hutool.core.util.idutil;
import com.google.common.base.joiner;
import com.google.common.base.splitter;
import org.bytedeco.javacpp.loader;

import java.io.file;
import java.text.messageformat;
import java.util.arrays;
import java.util.list;

/**
 * @program: csdn @classname: cutouttool @author: 剑客阿良_aliang @date: 2022-01-23 18:27 @description:
 * 裁剪工具 @version: v1.0
 */
public class cutouttool {
  /**
   * 图片裁剪
   *
   * @param imagepath 图片地址
   * @param outputdir 临时目录
   * @param startx 裁剪起始x坐标
   * @param starty 裁剪起始y坐标
   * @param weight 裁剪宽度
   * @param height 裁剪高度
   * @throws exception 异常
   */
  public static string cutoutimage(
      string imagepath,
      string outputdir,
      integer startx,
      integer starty,
      integer weight,
      integer height)
      throws exception {
    list<string> paths = splitter.on(".").splittolist(imagepath);
    string ext = paths.get(paths.size() - 1);
    if (!arrays.aslist("png", "jpg").contains(ext)) {
      throw new exception("format error");
    }
    string resultpath =
        joiner.on(file.separator).join(arrays.aslist(outputdir, idutil.simpleuuid() + "." + ext));
    string ffmpeg = loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
    processbuilder builder =
        new processbuilder(
            ffmpeg,
            "-i",
            imagepath,
            "-vf",
            messageformat.format(
                "crop={0}:{1}:{2}:{3}",
                string.valueof(weight),
                string.valueof(height),
                string.valueof(startx),
                string.valueof(starty)),
            "-y",
            resultpath);
    builder.inheritio().start().waitfor();
    return resultpath;
  }

  public static void main(string[] args) throws exception {
    system.out.println(
        cutoutimage(
            "c:\\users\\yi\\desktop\\2054011.jpg", "c:\\users\\yi\\desktop\\", 0, 0, 1920, 2160));
  }
}

代码说明:

1、cutoutimage方法参数分别为图片路径、输出临时目录、起始坐标x值、起始坐标y值、裁剪宽度、裁剪高度。

2、采用uuid作为临时输出唯一id,避免重复。

3、对文件后缀格式做了校验,可以按照需求自行调整。

4、裁剪尺寸不能超出图片限制,按照需求自行调整。

验证一下

准备的图片如下

Java实现图片裁剪功能的示例详解

执行结果

ffmpeg version 4.3.2 copyright (c) 2000-2021 the ffmpeg developers
  built with gcc 10.2.0 (rev5, built by msys2 project)
  configuration: --prefix=.. --disable-iconv --disable-opencl --disable-sdl2 --disable-bzlib --disable-lzma --disable-linux-perf --enable-shared --enable-version3 --enable-runtime-cpudetect --enable-zlib --enable-libmp3lame --enable-libspeex --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libvo-amrwbenc --enable-openssl --enable-libopenh264 --enable-libvpx --enable-libfreetype --enable-libopus --enable-cuda --enable-cuvid --enable-nvenc --enable-libmfx --enable-w32threads --enable-indev=dshow --target-os=mingw32 --cc='gcc -m64' --extra-cflags=-i../include/ --extra-ldflags=-l../lib/ --extra-libs='-static-libgcc -static-libstdc++ -wl,-bstatic -lstdc++ -lgcc_eh -lws2_32 -lcrypt32 -lpthread -lz -lm -wl,-bdynamic -lole32 -luuid'
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
input #0, image2, from 'c:\users\yi\desktop\2054011.jpg':
  duration: 00:00:00.04, start: 0.000000, bitrate: 255438 kb/s
    stream #0:0: video: mjpeg (progressive), yuvj444p(pc, bt470bg/unknown/unknown), 3840x2160, 25 tbr, 25 tbn, 25 tbc
stream mapping:
  stream #0:0 -> #0:0 (mjpeg (native) -> mjpeg (native))
press [q] to stop, [?] for help
output #0, image2, to 'c:\users\yi\desktop\\d1013fbee79e4380a01c574addf72afb.jpg':
  metadata:
    encoder         : lavf58.45.100
    stream #0:0: video: mjpeg, yuvj444p(pc), 1920x2160, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    metadata:
      encoder         : lavc58.91.100 mjpeg
    side data:
      cpb: bitrate max/min/avg: 0/0/200000 buffer size: 0 vbv_delay: n/a
frame=    1 fps=0.0 q=10.4 lsize=n/a time=00:00:00.04 bitrate=n/a speed=0.201x    
video:234kb audio:0kb subtitle:0kb other streams:0kb global headers:0kb muxing overhead: unknown
c:\users\yi\desktop\\d1013fbee79e4380a01c574addf72afb.jpg

process finished with exit code 0

结果图如下

Java实现图片裁剪功能的示例详解

以上就是java实现图片裁剪功能的示例详解的详细内容,更多关于java图片裁剪的资料请关注其它相关文章!