Question

I am using to load my images with high resolution and zoom quality with the tutorial: https://github.com/davemorrissey/subsampling-scale-image-view

It uses images from Assets. How I could do to load images from a URL?

Was it helpful?

Solution

The class SubsamplingScaleImageView has also a method to load an image that isn't from Assets:

SubsamplingScaleImageView.setImageFile(String extFile)

So you can get the image from the URL and save it on internal storage. Then you can load the image using the path from internal storage. To get the image as a Bitmap from an URL:

URL myFileUrl = new URL (StringURL);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();

InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);

To save the Bitmap on internal storage:

FileOutputStream out = new FileOutputStream(context.getCacheDir() + filename);
bm.compress(Bitmap.CompressFormat.PNG, 90, out);
// Don't forget to add a finally clause to close the stream

Finally

SubsamplingScaleImageView imageView =  (SubsamplingScaleImageView)findViewById(R.id.imageView);
imageView.setImageFile(context.getCacheDir() + filename);

OTHER TIPS

I actually solved this by creating a Bitmap from the provided URL string extra, although I think this may defeat the purpose of SubsamplingScaleImageView because I'm loading the entire Bitmap.

private void locateImageView() throws URISyntaxException, IOException {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    if (bundle.getString("imageUrl") != null) {
        String imageUrl = bundle.getString("imageUrl");
        Log.w(getClass().toString(), imageUrl);

        imageView = (SubsamplingScaleImageView) findViewById(R.id.image);

        URL newUrl = new URL(imageUrl);

        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);

            imageView.setImage(ImageSource.bitmap(myBitmap));

        } catch (IOException e) {
            // Log exception
            Log.w(getClass().toString(), e);
        }

    }
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top