Created
December 26, 2016 09:01
-
-
Save junbaor/631557ad337fcc90b2a4b1f8307bcb24 to your computer and use it in GitHub Desktop.
裁剪文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final String SRC = "D:\\Screenshot_2016-12-26-13-59-44-263_支付宝.png"; | |
public static void main(String[] args) throws IOException { | |
cutImage(SRC, "D:\\out\\src_out_" + 0 + ".png", 475, 1568, 489, 491); | |
} | |
/** | |
* 裁剪图片 | |
* | |
* @param sourcePath 源文件 | |
* @param targetPath 结果文件,如果为空结果文件会覆盖源文件 | |
* @param x 裁剪起始位置 x坐标 | |
* @param y 裁剪起始位置 y坐标 | |
* @param width 裁剪宽度 | |
* @param height 裁剪高度 | |
* @return | |
* @throws IOException 未找到源文件 | |
*/ | |
public static String cutImage(String sourcePath, String targetPath, int x, int y, int width, int height) throws IOException { | |
File imageFile = new File(sourcePath); | |
if (!imageFile.exists()) { | |
throw new IOException("Not found the images:" + sourcePath); | |
} | |
if (targetPath == null || targetPath == "") { | |
targetPath = sourcePath; | |
} | |
String format = sourcePath.substring(sourcePath.lastIndexOf(".") + 1, sourcePath.length()); | |
BufferedImage image = ImageIO.read(imageFile); | |
image = image.getSubimage(x, y, width, height); | |
ImageIO.write(image, format, new File(targetPath)); | |
return targetPath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment