如何从WAMP服务器下载图像文件


How to download an image file from WAMP server?

作为一个新手在android和PHP得到很多的斗争,这里是一个新的。

我成功地从我的android应用程序上传了一个图像到WAMP服务器。我使用的过程是,从SD卡中选择一张图像,将其放在图像视图中,相同的图像将被上传到WAMP服务器的目录"www'Images"中。

现在,反过来,当用户成功登录系统时,他/她应该在图像视图中看到他/她最后上传的图像。

这个过程工作良好,直到上传图像到服务器上。但是我无法下载相同的图像。

我尝试了如下操作,

 ImageView imcage = (ImageView)findViewById(R.id.ObjImgNormalUser);
 //start the download
 Bundle bundle = getIntent().getExtras();
 String usrName = bundle.getString("usrName");
 String Url = "http://172.25.64.188/Images/";
 Url = Url + "ABC";  //image name on server
 Url = Url + ".JPG";
 try 
 {
    InputStream inputStream =  (InputStream)new URL(Url).getContent();
    Bitmap bmp = BitmapFactory.decodeStream(inputStream);
    imcage.setImageBitmap(bmp);
 }

但它不工作。

请告诉我如何从WAMP服务器下载图像并在android应用程序的图像视图中显示它。

应该这样做:

URL url = new URL("http://www.yourdomain/your/path/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
final InputStream input = connection.getInputStream();
Bitmap yourpic = BitmapFactory.decodeStream(input);

然而,一些澄清:

  • 这是一个网络操作,您必须在ThreadAsyncTask中运行

  • 我建议使用以上代码仅用于测试目的或图像非常小的情况。

  • 如果你需要在后台加载更多的图片而不干扰用户与你的应用程序交互的能力,我建议使用Lazy Loading

将url传递给此方法,并将bmp设置为imageview

public Bitmap getImage(String url){
        Bitmap bmp =null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse getResponse = null;
        try {
            getResponse = client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String entityContents="";
        HttpEntity responseEntity = getResponse.getEntity();
        BufferedHttpEntity httpEntity = null;
        try {
            httpEntity = new BufferedHttpEntity(responseEntity);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        InputStream imageStream = null;
        try {
            imageStream = httpEntity.getContent();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        bmp = BitmapFactory.decodeStream(imageStream);
        return bmp;
    }

记住通过asynctask调用这个方法,因为它是一个网络操作,你应该总是在后台执行