[英]Does Glide have a method for loading both PNG and SVG?
I'm using Glide to load some images asynchronously into some of my ImageView
s, and I know it can handle images like PNG
or JPG
as it can handle SVG
.我正在使用Glide将一些图像异步加载到我的一些
ImageView
,我知道它可以处理PNG
或JPG
等图像,因为它可以处理SVG
。
Thing is, As far as I know, the way I load those two kinds of image differs.事情是,据我所知,我加载这两种图像的方式不同。 Like:
喜欢:
Loading "normal" images加载“正常”图像
Glide.with(mContext)
.load("URL")
.into(cardHolder.iv_card);
Loading SVG加载 SVG
GenericRequestBuilder<Uri, InputStream, SVG, PictureDrawable> requestBuilder = Glide.with(mContext)
.using(Glide.buildStreamModelLoader(Uri.class, mContext), InputStream.class)
.from(Uri.class)
.as(SVG.class)
.transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
.sourceEncoder(new StreamEncoder())
.cacheDecoder(new FileToStreamDecoder<>(new SVGDecoder()))
.decoder(new SVGDecoder())
.listener(new SvgSoftwareLayerSetter<Uri>());
requestBuilder
.diskCacheStrategy(DiskCacheStrategy.NONE)
.load(Uri.parse("URL"))
.into(cardHolder.iv_card);
And if I try to load SVG with the first method it won't work.如果我尝试使用第一种方法加载 SVG,它将无法正常工作。 If I try to load PNG or JPG with the second method, it won't work either.
如果我尝试用第二种方法加载 PNG 或 JPG,它也不起作用。
Is there a generic way to load both image types using Glide?有没有一种通用的方法来使用 Glide 加载两种图像类型?
The server where I'm fetching those images from don't tell me the image type before I download it.我从中获取这些图像的服务器在我下载之前不会告诉我图像类型。 It's a REST server and the resource will be retrieved in a way like
"http://foo.bar/resource"
.它是一个 REST 服务器,资源将以
"http://foo.bar/resource"
类的方式检索。 The only way to know the image type is reading the HEAD response.了解图像类型的唯一方法是读取 HEAD 响应。
You can use Glide & AndroidSVG together to achieve your goal.您可以结合使用Glide和AndroidSVG来实现您的目标。
There is sample from Glide for SVG.有来自 Glide for SVG 的示例。 Sample Example
示例
Setup RequestBuilder
设置请求生成器
requestBuilder = Glide.with(mActivity)
.using(Glide.buildStreamModelLoader(Uri.class, mActivity), InputStream.class)
.from(Uri.class)
.as(SVG.class)
.transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
.sourceEncoder(new StreamEncoder())
.cacheDecoder(new FileToStreamDecoder<SVG>(new SvgDecoder()))
.decoder(new SvgDecoder())
.placeholder(R.drawable.ic_facebook)
.error(R.drawable.ic_web)
.animate(android.R.anim.fade_in)
.listener(new SvgSoftwareLayerSetter<Uri>());
Use RequestBuilder with uri
使用带有 uri 的 RequestBuilder
Uri uri = Uri.parse("http://upload.wikimedia.org/wikipedia/commons/e/e8/Svg_example3.svg");
requestBuilder
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
// SVG cannot be serialized so it's not worth to cache it
.load(uri)
.into(mImageView);
This way you can achieve your goal.这样你就可以实现你的目标。 I hope this is helpful.
我希望这是有帮助的。
I added a flexible decoding pipeline to decode an image or SVG, maybe can help!我添加了一个灵活的解码管道来解码图像或 SVG,也许可以提供帮助! based on glide SVG example
基于滑动 SVG 示例
Decoder
解码器
class SvgOrImageDecoder : ResourceDecoder<InputStream, SvgOrImageDecodedResource> {
override fun handles(source: InputStream, options: Options): Boolean {
return true
}
@Throws(IOException::class)
override fun decode(
source: InputStream, width: Int, height: Int,
options: Options
): Resource<SvgOrImageDecodedResource>? {
val array = source.readBytes()
val svgInputStream = ByteArrayInputStream(array.clone())
val pngInputStream = ByteArrayInputStream(array.clone())
return try {
val svg = SVG.getFromInputStream(svgInputStream)
try {
source.close()
pngInputStream.close()
} catch (e: IOException) {}
SimpleResource(SvgOrImageDecodedResource(svg))
} catch (ex: SVGParseException) {
try {
val bitmap = BitmapFactory.decodeStream(pngInputStream)
SimpleResource(SvgOrImageDecodedResource(bitmap = bitmap))
} catch (exception: Exception){
try {
source.close()
pngInputStream.close()
} catch (e: IOException) {}
throw IOException("Cannot load SVG or Image from stream", ex)
}
}
}
Transcoder
转码器
class SvgOrImageDrawableTranscoder : ResourceTranscoder<SvgOrImageDecodedResource, PictureDrawable> {
override fun transcode(
toTranscode: Resource<SvgOrImageDecodedResource>,
options: Options
): Resource<PictureDrawable>? {
val data = toTranscode.get()
if (data.svg != null) {
val picture = data.svg.renderToPicture()
val drawable = PictureDrawable(picture)
return SimpleResource(drawable)
} else if (data.bitmap != null)
return SimpleResource(PictureDrawable(renderToPicture(data.bitmap)))
else return null
}
private fun renderToPicture(bitmap: Bitmap): Picture{
val picture = Picture()
val canvas = picture.beginRecording(bitmap.width, bitmap.height)
canvas.drawBitmap(bitmap, null, RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat()), null)
picture.endRecording();
return picture
}
Decoded Resource
解码资源
data class SvgOrImageDecodedResource(
val svg:SVG? = null,
val bitmap: Bitmap? = null)
Glide Module
滑翔模块
class AppGlideModule : AppGlideModule() {
override fun registerComponents(
context: Context, glide: Glide, registry: Registry
) {
registry.register(SvgOrImageDecodedResource::class.java, PictureDrawable::class.java, SvgOrImageDrawableTranscoder())
.append(InputStream::class.java, SvgOrImageDecodedResource::class.java, SvgOrImageDecoder())
}
// Disable manifest parsing to avoid adding similar modules twice.
override fun isManifestParsingEnabled(): Boolean {
return false
}
} }
ALTERNATIVE WAY : kotlin + Coil替代方式:kotlin + 线圈
This solution will work well with .svg , .png , .jpg此解决方案适用于 .svg 、 .png 、 .jpg
add dependency:添加依赖:
//Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:1.2.0")
implementation("io.coil-kt:coil-svg:1.2.0")
add this function to your code:将此函数添加到您的代码中:
fun ImageView.loadUrl(url: String) {
val imageLoader = ImageLoader.Builder(this.context)
.componentRegistry { add(SvgDecoder(this@loadSvg.context)) }
.build()
val request = ImageRequest.Builder(this.context)
.crossfade(true)
.crossfade(500)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.data(url)
.target(this)
.build()
imageLoader.enqueue(request)
}
Then call this method in your activity or fragment:然后在您的活动或片段中调用此方法:
imageView.loadUrl(url)
// url example : https://upload.wikimedia.org/wikipedia/commons/3/36/Red_jungle_fowl_white_background.png
GlideToVectorYou没有工作适合我,所以我用的线圈与线圈SVG扩展库
For others who reach this thread because they're looking for a way to load SVG's in Xamarin Android, the accepted answer won't work because a lot of those classes / methods don't seem to be available in the Xamarin Glide nuget package.对于其他人因为他们正在寻找一种在 Xamarin Android 中加载 SVG 的方法而到达此线程的其他人,接受的答案将不起作用,因为 Xamarin Glide nuget 包中似乎没有很多这些类/方法。 Here is what worked for me:
这是对我有用的:
public static void SetSvgFromBytes (this ImageView imageView, byte[] bytes, int width, int height) {
// Load the SVG from the bytes.
var stream = new MemoryStream (bytes);
var svg = SVG.GetFromInputStream (stream);
// Create a Bitmap to render our SVG to.
var bitmap = Bitmap.CreateBitmap (width, height, Bitmap.Config.Argb8888);
// Create a Canvas to use for rendering.
var canvas = new Canvas (bitmap);
canvas.DrawRGB (255, 255, 255);
// Now render the SVG to the Canvas.
svg.RenderToCanvas (canvas);
// Finally, populate the imageview from the Bitmap.
imageView.SetImageBitmap (bitmap);
}
It requires the AndroidSVG.Xamarin nuget package.它需要AndroidSVG.Xamarin nuget 包。
For Glide 4+ use this library called GlideToVectorYou which uses Glide internally.对于 Glide 4+,使用这个名为GlideToVectorYou 的库,它在内部使用 Glide。
fun ImageView.loadSvg(url: String?) {
GlideToVectorYou
.init()
.with(this.context)
.setPlaceHolder(R.drawable.loading, R.drawable.actual)
.load(Uri.parse(url), this)
}
Source: How to load remote svg files with Picasso library来源: 如何使用毕加索库加载远程 svg 文件
I also faced the same problem what i have done solved my problem you just have 2 do 2 things which work perfectly Go to the link https://github.com/corouteam/GlideToVectorYou 1- just copy past maven dependancy to project build allprojects { repositories { ... maven { url 'https://jitpack.io' } } } 2-add the dependency in app build like implementation 'com.github.corouteam:GlideToVectorYou:v2.0.0'我也遇到了同样的问题,我所做的解决了我的问题,您只需 2 做 2 件工作完美的事情转到链接https://github.com/corouteam/GlideToVectorYou 1- 只需复制过去的 maven 依赖项即可构建所有项目 {存储库 { ... maven { url 'https://jitpack.io' } } } 2-在应用程序构建中添加依赖项,如实现 'com.github.corouteam:GlideToVectorYou:v2.0.0'
thanks it will resolve to load the svg make sure that you are loading same as i am doing谢谢它会决定加载 svg 确保你加载的和我正在做的一样
Glide.with(holder.itemView.getContext()) .load(imageurl) .apply(new RequestOptions() .placeholder(R.drawable.placeholder) .dontAnimate() .fitCenter()) .into(holder.image); Glide.with(holder.itemView.getContext()) .load(imageurl) .apply(new RequestOptions() .placeholder(R.drawable.placeholder) .dontAnimate() .fitCenter()) .into(holder.image);
In case anyone still needs it, with Glide v4 you can use Glide-SVG library for adding SVG support easily to Glide.如果有人仍然需要它,使用 Glide v4,您可以使用Glide-SVG库轻松地向 Glide 添加 SVG 支持。 You only need to import Android SVG library too, and you can render any SVG with Glide using this simple, standard line of code:
您也只需要导入Android SVG库,并且您可以使用以下简单、标准的代码行使用 Glide 渲染任何 SVG:
GlideApp.with(this).load(url).into(imageView)
where GlideApp is your locally generated Glide Module, like the following:其中 GlideApp 是您本地生成的 Glide 模块,如下所示:
@GlideModule
class GlideModule : AppGlideModule() {
override fun isManifestParsingEnabled() = false
override fun applyOptions(context: Context, builder: GlideBuilder) {
super.applyOptions(context, builder)
builder.setLogLevel(Log.DEBUG)
}
}
Use the Sharp library, in place of the Glide library使用 Sharp 库代替 Glide 库
implementation 'com.pixplicity.sharp:library:1.1.0'
InputStream stream = response.body().byteStream();
Sharp.loadInputStream(stream).into(target);
stream.close();
An example can be seen here https://www.geeksforgeeks.org/how-to-load-svg-from-url-in-android-imageview/可以在这里看到一个例子https://www.geeksforgeeks.org/how-to-load-svg-from-url-in-android-imageview/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.