2014-02-20 57 views
2

我试图从http响应中获取图像,但未能将该流转换为位图。 请让我知道,我在这里错过了什么。从Android的httpResponse获取图像内容

仅供参考 - 图像内容以原始二进制形式接收&其jpeg图像。

步骤如下:

  1. 制作的HttpRequest。
  2. 作为响应,请检查200 - >获取httpentity内容。
  3. 使用BitMap工厂将流转换为位图。
  4. 将位图的ImageView

中的的AsyncTask

HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet(endpoint); 
    // Adding Headers .. 
    // Execute the request 
    HttpResponse response; 
    try { 
     response = httpclient.execute(httpget); 
    if (response.getStatusLine().getStatusCode() == 200) { 
     // Get hold of the response entity 
     HttpEntity entity = response.getEntity(); 
     if (entity != null) { 
     InputStream instream = entity.getContent(); 
     return instream; 
     // instream.close(); 
      } 
    } 
} 

postExecute这样做在的AsyncTask

if (null != instream) { 
     Bitmap bm = BitmapFactory.decodeStream(instream); 
     if(null == bm){ 
    Toast toast = Toast.makeText(getApplicationContext(), 
     "Bitmap is NULL", Toast.LENGTH_SHORT); 
      toast.show(); 
    } 
     ImageView view = (ImageView) findViewById(R.id.picture_frame); 
    view.setImageBitmap(bm); 
    } 

致谢postExecute提前这样做。

回答

4

终于找到了答案。下面是代码片段 - 可能有助于newbees使用http响应。

HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget = new HttpGet(endpoint); 
// Adding Headers .. 
// Execute the request 
HttpResponse response; 
try { 
    response = httpclient.execute(httpget); 
if (response.getStatusLine().getStatusCode() == 200) { 
    // Get hold of the response entity 
    HttpEntity entity = response.getEntity(); 
    if (entity != null) { 
    InputStream instream = entity.getContent(); 
    String path = "/storage/emulated/0/YOURAPPFOLDER/FILENAME.EXTENSION"; 
    FileOutputStream output = new FileOutputStream(path); 
    int bufferSize = 1024; 
    byte[] buffer = new byte[bufferSize]; 
    int len = 0; 
    while ((len = instream.read(buffer)) != -1) { 
     output.write(buffer, 0, len); 
    } 
    output.close(); 
} 

而不是将文件保存到磁盘,我们可以在bytearray中有内容并从中获取位图。

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
int bufferSize = 1024; 
byte[] buffer = new byte[bufferSize]; 
int len = 0; 
try { 
    // instream is content got from httpentity.getContent() 
    while ((len = instream.read(buffer)) != -1) { 
    baos.write(buffer, 0, len); 
    } 
    baos.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
byte[] b = baos.toByteArray(); 
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length); 
ImageView imageView = (ImageView)findViewById(R.id.picture_frame); 
imageView.setImageBitmap(bmp); 

仅供参考 - 在Android的fileoutput流写入到本地磁盘必须在非UI线程来完成(在我的情况下&那部分不加入使用异步任务)。

谢谢..

1

使用此库处理来自网站的图像。 https://github.com/nostra13/Android-Universal-Image-Loader 它为你做了一切。 但是onPostExecute中的代码应该放在onDoInBackground中。 onPre和onPost执行代码将在主线程上执行,doInBackground是工作线程。 但在这种情况下只使用通用图像加载器

+0

谢谢,不想使用其他库。目的是在单个图书馆中处理所有请求和响应。 – Dinesh