-1

I have used:

InputStream in;
Bitmap bmp=BitmapFactory.decodeStream(in);

but the process waits for a long time and nothing happens. On the server side, i have the image converted into byte[].

4

2 回答 2

2

我认为这段代码对你有用:

public Bitmap DownloadImage(String url)
{
    HttpClient client = new DefaultHttpClient();
    HttpResponse httpResponse;
    Bitmap bmp = null;

    try{
       httpResponse = client.execute(new HttpGet(url));
       responseCode = httpResponse.getStatusLine().getStatusCode();

       HttpEntity entity = httpResponse.getEntity();

       if (entity != null)
       {
           InputStream in = entity.getContent();
           bmp = BitmapFactory.decodeStream(in);
           in.close();
       }
    } catch (ClientProtocolException e)  {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }   
    return bmp;
}
于 2012-10-10T19:22:04.460 回答
0

尝试这种方式转换为位图。

 try {
     Bitmap bitmap=null;
         URL imageUrl = new URL(url);
     HttpURLConnection conn =
     (HttpURLConnection)imageUrl.openConnection();
     conn.setConnectTimeout(30000);
     conn.setReadTimeout(30000);
     conn.setInstanceFollowRedirects(true);
     InputStream is=conn.getInputStream();
     InputStream is;
     OutputStream os = new FileOutputStream(f);

     bitmap = decodeFile(f);
     return bitmap;
     } catch (Exception ex){
     ex.printStackTrace();
     return null;
     }

// decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }
于 2012-10-10T19:22:12.040 回答