package action;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Getpic {
public Getpic() {
}
public static boolean saveUrlAs(String fileUrl, String savePath)/* fileUrl网络资源地址 */
{
try {
/* 将网络资源地址传给,即赋值给url */
URL url = new URL(fileUrl);
/* 此为联系获得网络资源的固定格式用法,以便后面的in变量获得url截取网络资源的输入流 */
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
BufferedImage src = javax.imageio.ImageIO.read(in);
int width = src.getWidth();
int height = src.getHeight();
// 边长缩小为二分之一
BufferedImage tag = new BufferedImage(width / 2, height / 2, BufferedImage.TYPE_INT_RGB);
// 绘制缩小后的图
tag.getGraphics().drawImage(src, 0, 0, width / 2, height / 2, null);
FileOutputStream out1 = new FileOutputStream(savePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out1);
encoder.encode(tag);
out1.close();
return true;/* 网络资源截取并存储本地成功返回true */
} catch (Exception e) {
System.out.println(e + fileUrl + savePath);
return false;
}
}
public static void main(String[] args) {
Getpic pic = new Getpic();/* 创建实例 */
//需要下载的URL
String photoUrl = "http://hiphotos.baidu.com/yanshennan/pic/item/03a505c8bcbaf6557f3e6f8a.jpg";
// 截取最后/后的字符串
String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
//图片保存路径
String filePath = "E:";
/* 调用函数,并且进行传参 */
boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName);
System.out.println("Run ok!\n Get URL file " + flag);
System.out.println(filePath);
System.out.println(fileName);
}
}
java,取网络图片并缩小
最新推荐文章于 2024-07-23 04:09:09 发布
本文介绍了一个简单的Java程序,用于从指定的网络链接下载图片,并将其保存到本地文件系统。程序通过使用HttpURLConnection和ImageIO库来实现这一功能,包括处理网络请求、读取图片、缩放图片大小以及将缩放后的图片保存为JPEG格式。
6012

被折叠的 条评论
为什么被折叠?



