0

I found a amazing problem in downloading image.

The url of image is http://www.xbiquge.la/files/article/image/50/50353/50353s.jpg

I can open and save it in the chrome.but when I download it by the code,it fail.

I can't open it by the imageviewer.

Note:The size of wrong image is less than the right image file's.And other image of other website is ok.

I don't know what happen.Please help,Thanks advance

Following is my code

val imgUrl = "http://www.xbiquge.la/files/article/image/50/50353/50353s.jpg"
val conn = URL(imgUrl).openConnection()
val bytes = conn.getInputStream().readBytes()
File("D:\\test.jpg").writeBytes(bytes)

I also try to use java to download the image.it's also failure...

URL url = new URL("http://www.xbiquge.la/files/article/image/50/50353/50353s.jpg");
URLConnection connection=url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("d:\\download.jpg")));
int c;
byte[] temp = new byte[1024 * 2];
while ((c = bufferedInputStream.read(temp)) != -1) {
    bufferedOutputStream.write(temp,0,c);
}
bufferedOutputStream.close();
inputStream.close();
stars-one
  • 1
  • 3
  • Looks like it is not downloading the actual image but the html of the site it is trying to download from. Not sure about kotlin but there should be some equivalent of "allow redirect" that you should check. – Macindows Feb 13 '20 at 10:30
  • Maybe you are right.But I don't know how to do next.And I try to use java.But is also failure@Macindows – stars-one Feb 13 '20 at 11:52

2 Answers2

0

It looks like the question answered here: Kotlin: How to save image from Internet to internal storage

I think you need to specify the format and compressiontype of how you want the image to be saved.

Quadrivics
  • 181
  • 2
  • 10
  • thanks your answer,but I run the kotlin code in pc not in android.And I think the reason is not what you say.Because other internet picture can be downloaded successfully by this code. – stars-one Feb 13 '20 at 11:45
0

I found the right solution. The reason is that the file is gzip file. Must use following code to download it.

val openConnection = URL(url).openConnection()
//if the image file is gzip
val bytes = if (openConnection.contentEncoding == "gzip") {
    GZIPInputStream(openConnection.getInputStream()).readBytes()
} else {
    openConnection.getInputStream().readBytes()
}
val file = File("e:\\text.jpg")
file.writeBytes(bytes)
stars-one
  • 1
  • 3