从url下载图片--java与python实现方式比较
博客分类:
一、java的实现方式
- 首先读取图片
Java代码
- //方式一:直接根据url读取图片
- private static BufferedImage read(String imageUrl) throws IOException {
- URL url = new URL(imageUrl);
- BufferedImage image = ImageIO.read(url);
- return image;
- }
Java代码
- //如果需要设置connection里的一些属性,譬如RequestProperty,则采用方式二:
- private static BufferedImage read(String imageUrl) throws IOException {
- URL url = new URL(imageUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- //conn.setRequestProperty("Referer", referer);
- conn.setRequestMethod("GET");
- BufferedImage image = ImageIO.read(conn.getInputStream());
- return image;
- }
2. 然后保存图片
Java代码
- private static void save(BufferedImage image, String destImageUrl)
- throws IOException {
- File imageFile = new File(destImageUrl);
- FileOutputStream outStream = new FileOutputStream(imageFile);
- ImageIO.write(image, "jpg", outStream);
- ImageIO.write(image, "gif", outStream);
- ImageIO.write(image, "png", outStream);
- ImageIO.write(image, "jpeg", outStream);
- }
3. 如何获取图片的类型(jpg、Jpeg、gif、png等)
Java代码
- public static String get(byte[] imageBT) throws IOException {
- String type = "";
- MemoryCacheImageInputStream mcis = null;
- try {
- mcis = new MemoryCacheImageInputStream(new ByteArrayInputStream(
- imageBT));
- Iterator<ImageReader> it = ImageIO.getImageReaders(mcis);
- while (it.hasNext()) {
- ImageReader reader = (ImageReader) it.next();
- return reader.getFormatName();
- }
- } finally {
- if (mcis != null) {
- try {
- mcis.close();
- } catch (IOException ioe) {
- }
- }
- }
- return type;
- }
二、python如何实现
- 一行代码搞定图片读取和保存
Python代码
- from urllib import urlretrieve
- urlretrieve(‘http://img.chetx.com/chetxbbs/2005_04/09/1113039370066.gif’, ‘e://mypicture.gif’)
2. 一行代码搞定图片类型获取
Python代码
- import imghdr
- imghdr.what(‘mypicture.gif‘)
三、总结
相比于Java,python的实现真的是太简洁明了了
时间: 2024-10-13 23:38:01