Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to download a png using retrofit. I am trying to download the png from this url: http://wwwns.akamai.com/media_resources/globe_emea.png. What should be response Object to be specified in the Callback<> to achieve this.
As mentioned you shouldn't use Retrofit to actually download the image itself. If your goal is to simply download the content without displaying it then you could simply use an Http client like OkHttp which is another one of Square's libraries.
Here's a few lines of code which would have you download this image. You could then read the data from the InputStream.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://wwwns.akamai.com/media_resources/globe_emea.png")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
System.out.println("request failed: " + e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
response.body().byteStream(); // Read the data from the stream
}
});
Even though Retrofit isn't the man for the job to answer your question, the signature of your Interface definition would like this. But again don't do this.
public interface Api {
@GET("/media_resources/{imageName}")
void getImage(@Path("imageName") String imageName, Callback<Response> callback);
}
-
1This is a more complicated approach using byteStream and not so much flexible as in Picasso (caching, resizing, cropping etc.). – Yuraj Aug 24 '14 at 12:40
-
2The post mentions that this is an alternative only if you're just downloading content but aren't displaying it. Pradeem's use case doesn't specifically specify that he wants to display the content. – Miguel Lavigne Aug 24 '14 at 15:20
Of course we usually use Picasso to load image, but sometimes we really need use Retrofit to load a special image (like fetch a captcha image), you need add some header for request, get some value from header of response (of course you can also use Picasso + OkHttp, but in a project you have already use Retrofit to handle most of net requests), so here introduce how to implement by Retrofit 2.0.0 (I have already implemented in my project).
The key point is that you need use okhttp3.ResponseBody
to receive response, else Retrofit will parse the response data as JSON, not binary data.
codes:
public interface Api {
// don't need add 'Content-Type' header, it's useless
// @Headers({"Content-Type: image/png"})
@GET
Call<ResponseBody> fetchCaptcha(@Url String url);
}
Call<ResponseBody> call = api.fetchCaptcha(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
// display the image data in a ImageView or save it
Bitmap bmp = BitmapFactory.decodeStream(response.body().byteStream());
imageView.setImageBitmap(bmp);
} else {
// TODO
}
} else {
// TODO
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// TODO
}
});
-
Call is from okhhtp3 or retrofit2? – user2362956 Aug 8 '17 at 9:52
-
@user2362956 , the call from retrofit2, but the retrofit2 depends or uses okhttp3 in the bottom layer. – Spark.Bao Aug 9 '17 at 4:23
-
-
am getting this exception D/skia: --- SkAndroidCodec::NewFromStream returned null – Parthan_akon Nov 10 '20 at 3:54
Retrofit is a REST library, you can use Retrofit only to get image URL but for displaying Image you should use Picasso: http://square.github.io/picasso/
-
2
-
Declare it returning Call for instance:
@GET("/api/{api}/bla/image.png")
Call<ResponseBody> retrieveImageData();
then convert it to Bitmap yourself:
ResponseBody body = retrofitService.retrieveImageData().execute().body();
byte[] bytes = body.bytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
-
finally.......some one answered this. While using retrofit using bytestream to display the image won't work but when I used response.body().bytes() it worked perfectly fine.... Thanks @Alecio . I owe you alot... – Parthan_akon Nov 10 '20 at 4:16
Details
- Android studio 3.1.4
- Kotlin 1.2.60
- Retrofit 2.4.0
- checked in minSdkVersion 19
Solution
object RetrofitImage
object RetrofitImage {
private fun provideRetrofit(): Retrofit {
return Retrofit.Builder().baseUrl("https://google.com").build()
}
private interface API {
@GET
fun getImageData(@Url url: String): Call<ResponseBody>
}
private val api : API by lazy { provideRetrofit().create(API::class.java) }
fun getBitmapFrom(url: String, onComplete: (Bitmap?) -> Unit) {
api.getImageData(url).enqueue(object : retrofit2.Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
onComplete(null)
}
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
if (response == null || !response.isSuccessful || response.body() == null || response.errorBody() != null) {
onComplete(null)
return
}
val bytes = response.body()!!.bytes()
onComplete(BitmapFactory.decodeByteArray(bytes, 0, bytes.size))
}
})
}
}
Usage 1
RetrofitImage.getBitmapFrom(ANY_URL_STRING) {
// "it" - your bitmap
print("$it")
}
Usage 2
Extension for ImageView
fun ImageView.setBitmapFrom(url: String) {
val imageView = this
RetrofitImage.getBitmapFrom(url) {
val bitmap: Bitmap?
bitmap = if (it != null) it else {
// create empty bitmap
val w = 1
val h = 1
val conf = Bitmap.Config.ARGB_8888
Bitmap.createBitmap(w, h, conf)
}
Looper.getMainLooper().run {
imageView.setImageBitmap(bitmap!!)
}
}
}
Usage of the extension
imageView?.setBitmapFrom(ANY_URL_STRING)
-
@VarunRaj how did you detect lagging? Do you use this code in recycle view and it is laggy when you scroll it? – Vasily Bodnarchuk Sep 27 '19 at 13:01
-
Yes, I'm using this inside a recycler view. My recycler view is inside a nested scroll view it starts lagging as soon as images get in the screen – OhhhThatVarun Sep 27 '19 at 13:16
-
hm... it can be a problem. You will have to implement separate tasks queue for this actions (loading and rendering images). So, you just can't fun it without control on the main queue. – Vasily Bodnarchuk Sep 27 '19 at 13:20
You could also use Retrofit to perform the @GET
and just return the Response
. Then in code you can do isr = new BufferedInputStream(response.getBody().in())
to get the input stream of the image and write it into a Bitmap, say, by doing BitmapFactory.decodeStream(isr)
.
-
1Hi! i know its a quite old answer. I just wanted to add, that in retrofit 2.0 you have to return okhttp3.ResponseBody – Dima Feb 4 '16 at 10:46
-
1why use new BufferedInputStream instead of just calling
BitmapFactory.decodeStream(response.getBody().in())
? – KidA Nov 1 '16 at 21:34 -
java.io.IOException: closed am getting this error with "SkAndroidCodec::NewFromStream returned null" – Parthan_akon Nov 10 '20 at 4:01
I hope following code will help you:
Include following function inside MainActivity.java
:
void getRetrofitImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
Call<ResponseBody> call = service.getImageDetails();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
Log.d("onResponse", "Response came from server");
boolean FileDownloaded = DownloadImage(response.body());
Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
Following is the file handling code for image:
private boolean DownloadImage(ResponseBody body) {
try {
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
int width, height;
ImageView image = (ImageView) findViewById(R.id.imageViewId);
Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg");
width = 2*bMap.getWidth();
height = 6*bMap.getHeight();
Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
image.setImageBitmap(bMap2);
return true;
} catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
}
This is done using Android Retrofit 2.0. I hope it helped you.
Retrofit is encoding your byte array to base 64. So decode your string and you are good to go. In this way you can retrieve a list of images.
public static Bitmap getBitmapByEncodedString(String base64String) {
String imageDataBytes = base64String.substring(base64String.indexOf(",")+1);
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));
return BitmapFactory.decodeStream(stream);
}