如何使用KTOR客户端获取请求获取图像/PNG?
我正在尝试从客户端收到我的服务器的get请求。我使用Image/PNG内容类型的服务器响应。如何从Kotlin代码中收到图像?
I am trying to do a get request from a client get call to my server. My server response with a image/png content type. How can I recieve the image from my kotlin code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不仅可以下载图像,还可以下载任何其他文件。
创建
KTOR-CLIENT
,就像您通常这样做。对于使用此
客户端
下载文件,请阅读响应
使用bodyaschannel()
将响应读为bytereadChannel
。使用copyasChannel()
在磁盘上写入数据,传递目标bytewritechannel
。You can download not only an image but also any other file.
Create
ktor-client
as you usually do.For downloading a file using this
client
, readresponse
usingbodyAsChannel()
which reads the response asByteReadChannel
. UsecopyAsChannel()
to write the data on the disk, passing destination'sByteWriteChannel
.如果您不需要将图像保存在存储中,则可以使用ByTearray内存源来解码图像。
如果预期较大的图像,那么在解码之前将其降低会很好,请参见此处(Android) android:bitmapfactory.decodestream()在带有2MB Free Heap的400kb文件中退出
内存采样
ktor_version ='2.0.0'
。If you do not need to save image in storage, you can use byteArray memory source to decode image.
If larger images are expected it would be good to downscale them prior decoding, see here (Android) Android: BitmapFactory.decodeStream() out of memory with a 400KB file with 2MB free heap
Also note that Ktor api often changes from version to version, in this sample the
ktor_version = '2.0.0'
is used.我也面临这个问题。我通过像这样的目录的直接路径解决了这一问题:
基本上,这是产品JSON响应的路径:
基本上,您需要直接通过项目目录。
I was also facing this issue. And I resolved this one by passing the direct path of the directory like this:
basically, here is the path of the product json response:
Basically, you need to pass the project directory directly.
您将要从KTOR服务器提供 static Content : https://ktor.io/docs/serving-static-content.html
您创建一个静态文件夹,然后将图像放入其中:
设置后,您可以在该文件夹中引用文件。如果您也需要子文件夹中的文件,则可以添加一个额外的
文件(“。”)
line:You're going to want to serve static content from your Ktor server: https://ktor.io/docs/serving-static-content.html
You create a static folder, then put your images in there:
After that's set up, you can reference files in that folder. If you want files in subfolders as well, you can add an extra
files(".")
line: