美文网首页
JAVA截取图片后保存到本地

JAVA截取图片后保存到本地

作者: 羲九 | 来源:发表于2018-03-21 14:24 被阅读0次

    public static void cutImage(InputStream input, OutputStream out,String type, int x, int y, int width, int height)throws IOException {

    ImageInputStream imageStream = null;

    try {

    String imageType = (null == type || "".equals(type)) ? "jpg" : type;Iterator readers = ImageIO

    .getImageReadersByFormatName(imageType);

    ImageReader reader = readers.next();

    imageStream = ImageIO.createImageInputStream(input);

    reader.setInput(imageStream, true);

    ImageReadParam param = reader.getDefaultReadParam();

    Rectangle rect = new Rectangle(x, y, width, height);

    param.setSourceRegion(rect);

    BufferedImage bi = reader.read(0, param);

    ImageIO.write(bi, imageType, out);

    } finally {

    imageStream.close();

    input.close();

    out.close();

    }

    }

    使用示例:

    //locUrl为大图路径

    String[] targetRect=info.getTargetRect().split("/");

    //小图保存本地

    ImageUtils.cutImage(new FileInputStream(locUrl),new FileOutputStream(smallLoc),"jpg", Integer.parseInt(targetRect[0]),

    Integer.parseInt(targetRect[1]), Integer.parseInt(targetRect[2]), Integer.parseInt(targetRect[3]));

    相关文章

      网友评论

          本文标题:JAVA截取图片后保存到本地

          本文链接:https://www.haomeiwen.com/subject/mfdgqftx.html