Get image from httpResponse in Android

I am trying to get an image from an http response but cannot convert the stream to a bitmap. Please let me know what I'm missing here.

FYI - image content is accepted as raw binary and its jpeg image.

Sequencing:

  • Make an HttpRequest.
  • In response to check 200 -> get the content of httpentity.
  • convert stream to bitmap using BitMap factory.
  • Set the bitmap to image view

Doing this in postExecute 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();
            }
    }
}

Doing this in 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);
    }

Thanks at Advance.

+3
source share
2 answers

. - - , 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();
}

.

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);

FYI - android UI ( async, ​​).

..

+5

. https://github.com/nostra13/Android-Universal-Image-Loader . onPostExecute onDoInBackground. onPre onPost , doInBackground - .

+1

All Articles