一、java的实现方式
- 首先读取图片
//方式一:直接根据url读取图片 private static BufferedImage read(String imageUrl) throws IOException { URL url = new URL(imageUrl); BufferedImage image = ImageIO.read(url); return image; }
//如果需要设置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. 然后保存图片
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等)
public static String get(byte[] imageBT) throws IOException { String type = ""; MemoryCacheImageInputStream mcis = null; try { mcis = new MemoryCacheImageInputStream(new ByteArrayInputStream( imageBT)); Iteratorit = 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如何实现
- 一行代码搞定图片读取和保存
from urllib import urlretrieve urlretrieve(‘http://img.chetx.com/chetxbbs/2005_04/09/1113039370066.gif’, ‘e://mypicture.gif’)
2. 一行代码搞定图片类型获取
import imghdr imghdr.what(‘mypicture.gif')
三、总结
相比于Java,python的实现真的是太简洁明了了