public static void main(String[] args) {
// 需要镜像的图片路径
String URLName = "http://xxx/file/electric/20220727143421.png";
// 镜像后保存到本地的位置
String target = "C:\IMAGE\new.png";
try {
getUrlImg( URLName, target);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void getUrlImg(String URLName,String target) throws Exception {
URL url = new URL(URLName);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int httpResult = httpConnection.getResponseCode();
// 判断是否连接成功;
if (HttpResult != HttpURLConnection.HTTP_OK) {
return;
}
int filesize = urlconn.getContentLength();
int maxSize = 10240;//自定义最大可下载图片
if(filesize > maxSize){
return;
}
// 获取输入流
BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
// 输入流转图片文件
BufferedImage image = ImageIO.read(bis);
// 镜像处理
BufferedImage imageNew = flipImage(image, 1);
// 图片文件转输入流
InputStream in = bufferedImageToInputStream(imageNew);
if (in == null){
return;
}
// 创建输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
// 输入流缓冲
byte[] buffer = new byte[1024];
int num = -1;
while (true) {
// 读入到缓冲区
num = biss.read(buffer);
if (num == -1) {
bos.flush();
break;
}
bos.flush();
bos.write(buffer, 0, num);
}
bos.close();
bis.close();
in .close();
}
/**
* 将BufferedImage转换为InputStream
* @param image
* @return
*/
public static InputStream bufferedImageToInputStream(BufferedImage image){
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", os);
return new ByteArrayInputStream(os.toByteArray());
} catch (IOException e) {
log.error("提示:",e);
}
return null;
}
/**
* flipType 1 水平翻转 2 竖直翻转
*/
public static BufferedImage flipImage(BufferedImage source, Integer flipType) {
log.info("图片翻转-开始。" + flipType);
int width = source.getWidth();
int height = source.getHeight();
BufferedImage result = new BufferedImage(width, height, source.getType());
Graphics graphics = result.getGraphics();
try {
if (flipType != null && flipType.equals(2)) {
graphics.drawImage(source, 0, 0, width, height, 0, height, width, 0, null);
} else {
graphics.drawImage(source, 0, 0, width, height, width, 0, 0, height, null);
}
} catch (Exception e) {
log.error("图片翻转-异常", e);
} finally {
graphics.dispose();
source.flush();
}
log.info("图片翻转-结束");
return result;
}
如何将网络图片水平反转后保存到本地
最新推荐文章于 2022-12-23 20:03:49 发布