1

I would like to display an image from the URL that is providing me raw data for the image(png or JPG).

I checked this link but not much useful.

Here is my image link

I am processing the raw data but could not see the image. I am not sure how do I check that I got the right raw data.

here is my effort

private class DownloadImageTask extends AsyncTask<String, Void, Void> {

        byte[] bytes;
        Bitmap picture = null;

        @Override
        protected Void doInBackground(String... urls) {

//            final OkHttpClient client = new OkHttpClient();
//
//            Request request = new Request.Builder()
//                    .url(urls[0])
//                    .build();
//
//            Response response = null;
//
//            try {
//                response = client.newCall(request).execute();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            assert response != null;
//            if (response.isSuccessful()) {
//                try {
//                    assert response.body() != null;
//                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                    IOUtils.copy(response.body().byteStream(), baos);
//                    bytes = baos.toByteArray();
//                    picture = BitmapFactory.decodeStream(response.body().byteStream());
//                } catch (Exception e) {
//                    Log.e("Error", Objects.requireNonNull(e.getMessage()));
//                    e.printStackTrace();
//                }
//
//            }

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            try {
                URL url = new URL(urls[0]);
                byte[] chunk = new byte[4096];
                int bytesRead;
                InputStream stream = url.openStream();

                while ((bytesRead = stream.read(chunk)) > 0) {
                    outputStream.write(chunk, 0, bytesRead);
                }

            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

            bytes = outputStream.toByteArray();

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (bytes != null) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                cameraView.setImageBitmap(bitmap);
            }
//            cameraView.setImageBitmap(picture);

        }

    }
Arpit Patel
  • 7,212
  • 5
  • 56
  • 67

3 Answers3

1

The location of your problem/s in your workflow seems ill-determined. You should first identify this. (Plus, you did not specify if you are bound to a specific programming language).

For this sake, I suggest you:

  1. Start using a raw image file that you know is correct, and test its processing. There are quite a few raw image formats. Judging from the tag android, I guess the following can help:

    To capture a raw iamge into a file: How to capture raw image from android camera

    To display in ImageView: Can't load image from raw to imageview

    https://gamedev.stackexchange.com/questions/14046/how-can-i-convert-an-image-from-raw-data-in-android-without-any-munging

    https://developer.android.com/reference/android/graphics/ImageFormat

    https://www.androidcentral.com/raw-images-and-android-everything-you-need-know

  2. Try getting a raw image from an URL that you can manage.

  3. Apply this to the actual target URL.

This way you will know where your problem resides. Without more info it is hard to "debug" your problem.

You can also inspect code in FOSS projects.

  • Thank you for the response. Could you give me an example that retrieves raw data and display as an image in Android? – Arpit Patel Sep 10 '20 at 12:54
  • I checked all the references but couldn't see the proper way to display the raw image in android – Arpit Patel Sep 10 '20 at 14:46
  • @ArpitPatel - As mentioned, your task can be split into "subtasks". I was suggesting you first take some additional time to clarify where your problem resides, instead of asking for a complete code for the whole process. This is a way to help others help you, and it increases chances that you get your problem solved.. – sancho.s ReinstateMonicaCellio Sep 10 '20 at 15:49
  • I implemented the code but I am not getting any errors So I am just trying to identify the errors. Or what is wrong with my code if I am making any mistakes. – Arpit Patel Sep 10 '20 at 15:54
  • @ArpitPatel - As for showing in ImageView, please see updated answer. Again, please help narrowing down the problem. – sancho.s ReinstateMonicaCellio Sep 10 '20 at 15:56
  • If you guys need any more information please feel free to ask. – Arpit Patel Sep 10 '20 at 15:56
0

Identify the following questions:

Using URL to get bytes to load images

I wrote down what I can with reference to


class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
     @Override
     protected void onPostExecute(Bitmap bitmap) {
         super.onPostExecute(bitmap);
         imageView.setImageBitmap(bitmap);

     }

     @Override
     protected Bitmap doInBackground(String... strings) {
         try {
             OkHttpClient client = new OkHttpClient();
             Request request = new Request.Builder().url(strings[0]).build();
             Response response = client.newCall(request).execute();
             if (response.isSuccessful()) {
                 InputStream inputStream = response.body().byteStream();
                 return BitmapFactory.decodeStream(inputStream);
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
         return null;
     }
 }


This is the URL I use

https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/440px-Image_created_with_a_mobile_phone.png

https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg

I can test it. I hope it can help you

0

You could use a library named Picasso and do the following:

String url = get url from the Async Function and convert it to String
/*if you url has no image format, you could do something like this con convert the uri into a Bitmap*/


public Bitmap getCorrectlyOrientedImage(Context context, Uri uri, int maxWidth)throws IOException {

InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
try {
      input.close();

    } catch (NullPointerException e) {
            e.printStackTrace();
 }

/*trying to get the right orientation*/
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
            return null;
        }

int originalSize = Math.max(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth);

double ratio = (originalSize > maxWidth) ? (originalSize / maxWidth) : 1.0;

Matrix matrix = new Matrix();
        int rotationInDegrees = exifToDegrees(orientation);
        if (orientation != 0) matrix.preRotate(rotationInDegrees);

        int bmpWidth = 0;
        try {
            assert bitmap != null;
            bmpWidth = bitmap.getWidth();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

Bitmap adjustedBitmap = bitmap;
if (bmpWidth > 0)
   adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

return adjustedBitmap;
}

/*Then you has the image in Bitmap, you can use the solution below or if Picasso doesn't allows you to put Bitmap you can pass it directly to the ImageView as a Bitmap.*/

ImageView imageView = view.findViewById(R.id.imageViewId);

/*Then use Picasso to draw the image into the ImageView*/
Picasso.with(context).load(url).fit().into(imageView );

This is the dependency for build.gradle, not sure if is the last version but you could try.

implementation 'com.squareup.picasso:picasso:2.5.2'

Kind regards!

Alter
  • 903
  • 1
  • 11
  • 27
  • This URL doesn't provide jpg or png. I can not use URL directly I need to do processing to convert data to JPG or png. – Arpit Patel Sep 16 '20 at 14:52
  • How you are storing the image? I think with Picasso, no matter how is the url, it will just find the url and try to put whatever is there into the ImageView, did you already try? – Alter Sep 16 '20 at 14:55
  • I am using a third party URL to display the image so I am not sure how they store the data. – Arpit Patel Sep 16 '20 at 15:12
  • I updated my answer, so can convert the uri into a Bitmap and then assign it to the ImageView, hope it match to your needs. – Alter Sep 16 '20 at 15:14
  • I tried to download data as a bitmap but its not working you can see on my question. – Arpit Patel Sep 16 '20 at 15:17
  • Yes, I saw your question, but the solution is not the same – Alter Sep 16 '20 at 15:18
  • Are you able to see the image when debugging the app as a Bitmap already converted? – Alter Sep 16 '20 at 15:21