安卓:通过php从网络服务器下载图片


Android: download image from webserver through php

我想从安卓应用程序下载图像。但是,在应用程序中,我不知道图像的名称。

在 php 脚本中,我选择应用程序应该随机下载的图像文件,现在我有两个选择:

  1. 我可以回显图像文件名,然后应用程序可以直接下载文件
  2. 我可以回显整个图像数据

更好的方法是什么?如果是第一个,你能链接到一个关于如何下载图像的好页面吗?我可以轻松上传图像,但互联网上充满了如何下载图像的不同方式,所以我不知道哪一种是最好的......

我这样做的方式是第一种方法,图像 URL 存储在数据库中并通过 json 与其他数据一起检索,我使用以下代码从 URL 获取图像。

public class ImageDownloader {
public static Bitmap downloadImage(String url) throws MalformedURLException{
    return downloadImage(new URL(url));
}
public static Bitmap downloadImage(URL url){
    Bitmap bmImg = null;
    try {
    HttpURLConnection conn= (HttpURLConnection)url.openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream is = conn.getInputStream();
    bmImg = BitmapFactory.decodeStream(is);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return null;
    }

    return bmImg;
 }  
}

它返回位图

public static Bitmap getImage(String url){
        Bitmap img = null ;
        try {
            URL feedImage = new URL(url);
            HttpURLConnection conn= (HttpURLConnection)feedImage.openConnection();
            InputStream is = conn.getInputStream();
            img = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return img ;    
    }