2

I want to convert a URL to Bitmap image.i am also trying to compress and saving this bitmap on SD Card but when i run code, no image is displayed in Web Image-view. i have following code:

Logger.d(LOG_TAG, "Enter retrieveImageData()");
    URL url = new URL(imageUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(CONNECTTION_TIMEOUT);
    // determine the image size and allocate a buffer
    int fileSize = connection.getContentLength();
    if (fileSize < 0) {
        Logger.d(LOG_TAG, "retrieveImageData()->file size less than 0");
        return null;
    }
    byte[] imageData = null;

    byte[] buffer = new byte[BUFFER_SIZE];

    // download the file
    // if(Global.show_logs) Log.d(LOG_TAG, "fetching image " + imageUrl +
    // " (" + fileSize + ")");
    BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());

    if ((!(height == -1)) && (!(width == -1))) {
        Logger.d(LOG_TAG, "Enter retrieveImageData() :width="+width+" height"+height);
        File tmpFile = GlobalFunctions.getTmpFile();

        if (tmpFile == null)
            throw new IOException("DroidFu::ImageLoader: Could not create temp file!");

        BufferedOutputStream ostream = new BufferedOutputStream(new FileOutputStream(tmpFile));

        Logger.d(LOG_TAG, "before call of IOUtils.copy");
        IOUtils.copy(istream, ostream);
        Logger.d(LOG_TAG, "after call of IOUtils.copy");
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(tmpFile.getAbsolutePath(), options);

        // Calculate inSampleSize
        Logger.d(LOG_TAG, "before call of calculateInSampleSize()");
        options.inSampleSize = calculateInSampleSize(options, width, height);
        Logger.d(LOG_TAG, "after call of calculateInSampleSize()");

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Logger.d(LOG_TAG, "Absolute path of tmp file is: "+tmpFile.getAbsolutePath());
        Bitmap b=BitmapFactory.decodeFile(tmpFile.getAbsolutePath(), options);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 100, stream);

        byte[] byteArray = stream.toByteArray();

        b.recycle();
        //imageData = stream.toByteArray();

        istream.close();
        ostream.close();
        stream.close();
        Logger.d(LOG_TAG, "Exit retrieveImageData() after resizing to imageview");
        return byteArray;
    }

But this code throw exception (Throwable e) at this line and also " e " is null.:

b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
5
  • 8
    -1 for no posting stacktrace Commented Jan 4, 2013 at 8:36
  • StackTrace is not helpful(not informative), that's why ,i haven't share. Any how,if you can help me,i'll share. Commented Feb 22, 2013 at 6:14
  • @MohammadImran should we debug the code on the screen ? :-) You should share your stacktrace. Commented Feb 22, 2013 at 21:51
  • Is b null? Was it an IOException? These are all questions answered by posting your stack trace. No one will help you if you don't post relevant information. Commented Feb 24, 2013 at 2:32
  • Without the stack trace we have no idea what caused the error. It may be as simple as a NPE, but it could be something like networking on main thread. Where do you call the above code from? Why not post your stack trace? If you are voted up to +5, you will get all the reputation you posted back (you don't get it back if you simply don't select a correct answer). Commented Feb 26, 2013 at 21:14

3 Answers 3

10

Try this.

Convert Bitmap to Byte Array:-

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Convert Byte Array into Bitmap Image:-

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Sign up to request clarification or add additional context in comments.

1 Comment

@AliImran have a look at the dates. This was the first answer.
6

to convert bitmap into byte array you can use

        final int lnth=bitmap.getByteCount();

        ByteBuffer dst= ByteBuffer.allocate(lnth);
        bitmap.copyPixelsToBuffer( dst);
        byte[] barray=dst.array();

And to get bitmap from byte array use

Bitmap bitmap = new BitmapFactory().decodeByteArray(byte_array, 0/* starting index*/, byte_array.length/*no of byte to read*/)

Comments

4
+50

Here is the link for more advanced image Loader library

the usage is as below:

first put this code in your main activity.

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub).showImageOnFail(R.drawable.ic_error).showImageForEmptyUri(R.drawable.ic_empty_url).cacheInMemory().cacheOnDisc().build();
    // Create global configuration and initialize ImageLoader with this
    // configuration
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(defaultOptions).build();
    ImageLoader.getInstance().init(config);

then use it in your class like this:

private ImageLoader imageLoader;

inside your onCreate() method

imageLoader = ImageLoader.getInstance();

then load image like this

imageLoader.displayImage(IMG_URL, imageView);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.