最近无聊看了一下百度的图片搜索接口,于是想着利用这些接口写了个android版的图片搜索引擎。本来不打算写的,就当纪念一下晴雪吧。。
实现效果图
主要是利用百度的图片搜索引擎返回的代码进行解析,生成图片地址。
主要实现代码:
public void searchImage(View v){
word = keyWord.getText().toString();
if(word==null||"".equals(word.trim())){
Toast.makeText(this, "请输入搜索的图片关键字", Toast.LENGTH_LONG).show();
return;
}
try {
String path = "http://image.baidu.com/i?";
String param = "tn=baiduimagejson&ie=utf-8&ic=0&rn=20&pn="+page+"&word=" + URLEncoder.encode(word,"UTF-8");
String json = ImageUtil.sendGETRequest(path+param);
String str = new String (json.getBytes("GBK"),"UTF-8");
imageData = ImageUtil.resolveImageData(json);
loadData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageUtil主要是用来发送网络请求和解析图片地址,并提供图片文件保存。
public class ImageUtil {
public static List<String> getImageURL(String json) {
if (json == null || "".equals(json)) {
return null;
}
return null;
}
// 获取文件夹的字节大小
public static long getFileSize(File f) throws Exception {
long size = 0;
File flist[] = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSize(flist[i]);
} else {
size = size + flist[i].length();
}
}
return size;
}
public static String sendGETRequest(String path) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(path)
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//刚发现的问题,一定要加上,不然搜索的结果和我们用浏览器在百度搜索的结果不一样
conn.setRequestProperty("Cookie", "BAIDUID=EAAB2CC610BEEAB039E03726E6CF549B:FG=1");
// if (conn.getResponseCode() == 200) {
InputStream inStream = conn.getInputStream();
byte[] data = StreamTool.read(inStream);
String result = new String(data);
return result;
// }else{
// return null;
// }
}
public static List<String> resolveImageData(String json) throws Exception {
List<String> list = new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray data = object.getJSONArray("data");
for (int i = 0; i < data.length() - 1; i++) {
String objURL = data.getJSONObject(i).getString("objURL");
list.add(objURL);
}
return list;
}
public static void deleteFile(File f) {
if(f.exists()&&f.isDirectory()){
File[] files = f.listFiles();
for(File file:files){
file.delete();
}
}
}
public static boolean saveImageList(List<String> imageData)throws Exception {
for(String url : imageData){
saveImage(url);
}
return true;
}
public static boolean saveImage(String url) throws Exception{
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File f = new File(Environment.getExternalStorageDirectory()
+ "/netimage/image/");
if(!f.exists()){
f.mkdirs();
}
File temp = new File(Environment.getExternalStorageDirectory()
+ "/netimage/cache/" + MD5.getMD5(url));
if (temp.exists()) {
FileOutputStream out = new FileOutputStream(f.getPath()+"/"+getSystemTime()+".jpg");
FileInputStream in = new FileInputStream(temp);
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer))!=-1){
out.write(buffer, 0, len);
}
out.close();
in.close();
return true;
}
}
return false;
}
public static String getSystemTime(){
long time = System.currentTimeMillis();
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddhhmmss");
return sdf.format(date)+time%1000;
}
}
ImageBrowse类是显示单张图片的activity
public class ImageBrowse extends Activity implements OnTouchListener {
private ImageView My_view;
private int position;
private ArrayList<String> ImageList;
private static final String TAG = "ImageBrowse";
private int CheckedPosition;
public static int screenWidth;
public static int screenHeight;
private MyGallery gallery;
private boolean isScale = false;
private float beforeLenght = 0.0f;
private float afterLenght = 0.0f;
private float currentScale = 1.0f;
private Bitmap[] map;
private void init() {
Intent intent = getIntent();
int flag = intent.getIntExtra("flag", 0);
ImageList = intent.getStringArrayListExtra("ImageAddress");
position = intent.getIntExtra("position", 0);
CheckedPosition = position * 2 + flag + 1;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_image_browse);
gallery = (MyGallery) findViewById(R.id.mygallery);
gallery.setVerticalFadingEdgeEnabled(false);
init();
gallery.setHorizontalFadingEdgeEnabled(false);
try {
map = SyncImageLoader.loadSingleImage(ImageList);
gallery.setAdapter(new GalleryAdapter(this, map));
if(CheckedPosition>map.length){
CheckedPosition = map.length;
}
gallery.setSelection(CheckedPosition - 1);
} catch (Exception e) {
e.printStackTrace();
}
screenWidth = getWindow().getWindowManager().getDefaultDisplay()
.getWidth();
screenHeight = getWindow().getWindowManager().getDefaultDisplay()
.getHeight();
}
private class GalleryChangeListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
currentScale = 1.0f;
isScale = false;
beforeLenght = 0.0f;
afterLenght = 0.0f;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
public boolean onTouch(View v, MotionEvent event) {
Log.i("lyc", "touched---------------");
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
beforeLenght = spacing(event);
if (beforeLenght > 5f) {
isScale = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (isScale) {
afterLenght = spacing(event);
if (afterLenght < 5f)
break;
float gapLenght = afterLenght - beforeLenght;
if (gapLenght == 0) {
break;
} else if (Math.abs(gapLenght) > 5f) {
float scaleRate = gapLenght / 854;
Animation myAnimation_Scale = new ScaleAnimation(
currentScale, currentScale + scaleRate,
currentScale, currentScale + scaleRate,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
myAnimation_Scale.setDuration(100);
myAnimation_Scale.setFillAfter(true);
myAnimation_Scale.setFillEnabled(true);
currentScale = currentScale + scaleRate;
gallery.getSelectedView().setLayoutParams(
new Gallery.LayoutParams(
(int) (480 * (currentScale)),
(int) (854 * (currentScale))));
beforeLenght = afterLenght;
}
return true;
}
break;
case MotionEvent.ACTION_POINTER_UP:
isScale = false;
break;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menu.add(1,1,1,"保存当前图片");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//响应每个菜单项(通过菜单项的ID)
case 1:
if(ImageList!=null&&ImageList.size()>0){
try {
int index = gallery.getSelectedItemPosition();
ImageUtil.saveImage(ImageList.get(index));
Toast.makeText(this, "图片保存在/netimage/image目录", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "图片保存失败", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}else{
Toast.makeText(this, "没有图片可以保存", Toast.LENGTH_LONG).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void finish() {
for(Bitmap bm : map){
if(bm!=null&&!bm.isRecycled()){
bm.recycle();
}
}
super.finish();
}
}
SyncImageLoader主要是实现ListView中的网络图片进行异步加载
public class SyncImageLoader {
private Object lock = new Object();
private boolean mAllowLoad = true;
private boolean firstLoad = true;
private int mStartLoadLimit = 0;
private int mStopLoadLimit = 0;
public static Bitmap[] bitmap = new Bitmap[0];
final Handler handler = new Handler();
private HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
public interface OnImageLoadListener {
public void onImageLoad(Integer t, Drawable drawable,int flag);
public void onError(Integer t,int flag);
}
public void setLoadLimit(int startLoadLimit, int stopLoadLimit) {
if (startLoadLimit > stopLoadLimit) {
return;
}
mStartLoadLimit = startLoadLimit;
mStopLoadLimit = stopLoadLimit;
}
public void restore() {
mAllowLoad = true;
firstLoad = true;
}
public void lock() {
mAllowLoad = false;
firstLoad = false;
}
public void unlock() {
mAllowLoad = true;
synchronized (lock) {
lock.notifyAll();
}
}
public void loadImage(Integer t, String imageUrl,
OnImageLoadListener listener, int flag) {
final OnImageLoadListener mListener = listener;
final String mImageUrl = imageUrl;
final Integer mt = t;
final int f = flag;
new Thread(new Runnable() {
@Override
public void run() {
if (!mAllowLoad) {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (mAllowLoad && firstLoad) {
loadImage(mImageUrl, mt, mListener,f);
}
if (mAllowLoad && mt <= mStopLoadLimit && mt >= mStartLoadLimit) {
loadImage(mImageUrl, mt, mListener,f);
}
}
}).start();
}
private void loadImage(final String mImageUrl, final Integer mt,
final OnImageLoadListener mListener,final int flag) {
if (imageCache.containsKey(mImageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(mImageUrl);
final Drawable d = softReference.get();
if (d != null) {
handler.post(new Runnable() {
@Override
public void run() {
if (mAllowLoad) {
mListener.onImageLoad(mt, d,flag);
}
}
});
return;
}
}
try {
final Drawable d = loadImageFromUrl(mImageUrl);
if (d != null) {
imageCache.put(mImageUrl, new SoftReference<Drawable>(d));
}
handler.post(new Runnable() {
@Override
public void run() {
if (mAllowLoad) {
mListener.onImageLoad(mt, d,flag);
}
}
});
} catch (IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
mListener.onError(mt,flag);
}
});
e.printStackTrace();
}
}
public static Drawable loadLagerImageFromUrl(String url) throws IOException {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File f = new File(Environment.getExternalStorageDirectory()
+ "/netimage/cache/" + MD5.getMD5(url));
if (f.exists()) {
FileInputStream fis = new FileInputStream(f);
Drawable d = Drawable.createFromStream(fis, "src");
return d;
}
URL m = new URL(url);
InputStream i = (InputStream) m.getContent();
DataInputStream in = new DataInputStream(i);
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
in.close();
out.close();
//Drawable d = Drawable.createFromStream(i, "src");
return loadImageFromUrl(url);
} else {
URL m = new URL(url);
InputStream i = (InputStream) m.getContent();
Drawable d = Drawable.createFromStream(i, "src");
i.close();
return d;
}
}
public static Drawable loadImageFromUrl(String url) throws IOException {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File f = new File(Environment.getExternalStorageDirectory()
+ "/netimage/cache/" + MD5.getMD5(url));
if (f.exists()) {
//FileInputStream fis = new FileInputStream(f);
//Drawable d = Drawable.createFromStream(fis, "src");
Bitmap bitmap = decodeSampledBitmapFromResource(f.getPath(), 0, 150, 150);
return new BitmapDrawable(bitmap);
}
URL m = new URL(url);
InputStream i = (InputStream) m.getContent();
DataInputStream in = new DataInputStream(i);
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
in.close();
out.close();
//Drawable d = Drawable.createFromStream(i, "src");
return loadImageFromUrl(url);
} else {
URL m = new URL(url);
InputStream i = (InputStream) m.getContent();
Drawable d = Drawable.createFromStream(i, "src");
i.close();
return d;
}
}
public static Bitmap[] loadSingleImage(ArrayList<String> list) throws Exception{
//Bitmap[] dra = new Bitmap[list.size()];
List<Bitmap> maps = new ArrayList<Bitmap>();
for(int i=0;i<list.size();){
File f = new File(Environment.getExternalStorageDirectory()
+ "/netimage/cache/" + MD5.getMD5(list.get(i)));
if (f.exists()) {
//Bitmap bitmap = decodeSampledBitmapFromResource(f.getPath(), 0, 490, 700);
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
// dra[i]= bitmap;
maps.add(bitmap);
i++;
}else{
list.remove(i);
}
/*}else{
URL m = new URL(list.get(i));
InputStream is = (InputStream) m.getContent();
DataInputStream in = new DataInputStream(is);
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int byteread = 0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
in.close();
out.close();
dra[i]= BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
}*/
}
Bitmap[] dra = new Bitmap[maps.size()];
for(int i=0;i<maps.size();i++){
dra[i] = maps.get(i);
}
return dra;
}
public static Bitmap decodeSampledBitmapFromResource(String res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(res, resId, options);
BitmapFactory.decodeFile(res,options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// return BitmapFactory.decodeResource(res, resId, options);
return BitmapFactory.decodeFile(res,options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
建议在wifi下使用
完整的代码下载地址