PhotoGrabber

从flickr上抓图下来,用downloadr也可以。用了flickr api的java wrapper – flickrj


package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.SearchParameters;

public class PhotoGrabber {
	public static String[] keywords = {"flower","animal","princess","spain","democracy","china","computer","science"
		,"cluster","winnner","soccer","cafe"};
	public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, FlickrException {
		String apiKey = "Your API Key";
		String secret = "Your Secret";
		Flickr flickr = new Flickr(apiKey,secret,new REST());
		PhotosInterface pi = flickr.getPhotosInterface();
		for(String key:keywords){
			SearchParameters searchParam = new SearchParameters();
			searchParam.setText(key);
			PhotoList result = pi.search(searchParam, 1000, 20);

			System.out.println(result.size());
			Iterator itr = result.iterator();
			while(itr.hasNext()){
				Photo p = (Photo) itr.next();
				URL urlt = new URL(p.getThumbnailUrl());
				URL url = new URL(p.getMediumUrl());
				InputStream is = url.openConnection().getInputStream();
				String fmt = p.getOriginalFormat();
				FileOutputStream fos = new FileOutputStream(new File("H:/tmp/medium/"+p.getId()+"."+fmt),true);
				byte[] buf = new byte[1024];
				int len = 0;
				   while ((len = is.read(buf)) > 0)
				   {
				      fos.write(buf, 0, len);
				   }
				is.close();
				fos.close();

				is = urlt.openConnection().getInputStream();
				fos = new FileOutputStream(new File("H:/tmp/thumb/"+p.getId()+"."+fmt),true);
				   while ((len = is.read(buf)) > 0)
				   {
				      fos.write(buf, 0, len);
				   }
				is.close();
				fos.close();
			}
		}

	}

}

 

Comments are closed.