gpui: Support loading image from filesystem (#6978)
This PR implements support for loading and displaying images from a local file using gpui's `img` element. API Changes: - Changed `SharedUrl` to `SharedUrl::File`, `SharedUrl::Network` Usage: ```rust // load from network img(SharedUrl::network(...)) // previously img(SharedUrl(...) // load from filesystem img(SharedUrl::file(...)) ``` This will be useful when implementing markdown image support, because we need to be able to render images from the filesystem (relative/absolute path), e.g. when implementing markdown preview #5064. I also added an example `image` to the gpui crate, let me know if this is useful. Showcase: <img width="872" alt="image" src="https://github.com/zed-industries/zed/assets/53836821/b4310a26-db81-44fa-9a7b-61e7d0ad4349"> **Note**: The example is fetching images from [Lorem Picsum](https://picsum.photos) ([Github Repo](https://github.com/DMarby/picsum-photos)), which is a free resource for fetching images in a specific size. Please let me know if you're okay with using this in the example.
This commit is contained in:
parent
b865db455d
commit
dd74643993
12 changed files with 210 additions and 90 deletions
|
@ -68,22 +68,31 @@ impl ImageCache {
|
|||
{
|
||||
let uri = uri.clone();
|
||||
async move {
|
||||
let mut response =
|
||||
client.get(uri.as_ref(), ().into(), true).await?;
|
||||
let mut body = Vec::new();
|
||||
response.body_mut().read_to_end(&mut body).await?;
|
||||
match uri {
|
||||
SharedUrl::File(uri) => {
|
||||
let image = image::open(uri.as_ref())?.into_bgra8();
|
||||
Ok(Arc::new(ImageData::new(image)))
|
||||
}
|
||||
SharedUrl::Network(uri) => {
|
||||
let mut response =
|
||||
client.get(uri.as_ref(), ().into(), true).await?;
|
||||
let mut body = Vec::new();
|
||||
response.body_mut().read_to_end(&mut body).await?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(Error::BadStatus {
|
||||
status: response.status(),
|
||||
body: String::from_utf8_lossy(&body).into_owned(),
|
||||
});
|
||||
if !response.status().is_success() {
|
||||
return Err(Error::BadStatus {
|
||||
status: response.status(),
|
||||
body: String::from_utf8_lossy(&body).into_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let format = image::guess_format(&body)?;
|
||||
let image =
|
||||
image::load_from_memory_with_format(&body, format)?
|
||||
.into_bgra8();
|
||||
Ok(Arc::new(ImageData::new(image)))
|
||||
}
|
||||
}
|
||||
|
||||
let format = image::guess_format(&body)?;
|
||||
let image = image::load_from_memory_with_format(&body, format)?
|
||||
.into_bgra8();
|
||||
Ok(Arc::new(ImageData::new(image)))
|
||||
}
|
||||
}
|
||||
.map_err({
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue