简体   繁体   中英

Unable to draw a bitmap as it is downloaded on a canvas

I'm downloading an image from a website which will be shown on an imageview.

i want the image to appear on the imageview as it is downloaded and not to wait for the entire image be downloaded . what i mean is if the image is 10000 bytes and the first bytes to be downloaded are 1024, then an image should be constructed from the 1024 bytes and form the part of image downloaded and draw it on a canvas

byte[] buffer =new byte[1024];
                int bytesRead = -1;
                byte[] writtenOnes;



                while((bytesRead = inputStream.read(buffer)) != -1){
                    fileOutputStream.write(buffer, 0, bytesRead);
                    fileOutputStream.flush();
                    filebytes = Files.toByteArray(media);
                    status = (100 * filebytes.length) / contentLength;
                    publishProgress(status);

                }
                fileOutputStream.flush();

                fileOutputStream.close();
                inputStream.close();

                if( media.length() == contentLength){
                    d(" WELL DONE, FILECOMPLETLY DOWNLOADED. SIZE IS "+ contentLength);
                }else{
                    d(" file not completely downloaded. bytes remaining "+(contentLength -media.length()));
                }
            }
            connection.disconnect();
            return  mediaFile;
        }catch(Exception exc){
            exc.printStackTrace();
            return "";
        }

    }

    protected void onProgressUpdate(Integer... status) {
        int state = status[0];
        incompleteBitmap =BitmapFactory.decodeByteArray(filebytes, 0, filebytes.length);

        d(" status is "+ state);
        canvas.drawBitmap(incompleteBitmap,0,0,new Paint(Paint.FILTER_BITMAP_FLAG));
        progressBar.setProgress(state);
    }

I'm unable to create a bitmap from the downloaded bytes. i get a NullpointerException when i try to get the formed bitmap on onProgressUpdate() method

Q: is there a way i can achieve this?

If the images are within your domain I have had great results achieving this effect using the Fresco image library which supports the progressive JPEG format. However this may not be desirable if you're looking for a full vanilla solution or are already using another image view library or if the images and format are outwith your control:

Fresco progressive JPEG documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM