mahdi
mahdi

Reputation: 16407

android:load svg file from web and show it on image view

I want to load a svg file from the web and show this file in an ImageView. For non vector images I use the Picasso library.

Is it possible to use this library for svg files as well?
Is there any way to load svg files from the web and show it in an ImageView?
I use the svg-android library to show svg files but i don't know how to get svg images from the web all the examples for this library use local files.

Upvotes: 36

Views: 63145

Answers (8)

Touhid
Touhid

Reputation: 1676

Kotlin and Coil Library to load SVG from URL:

  1. Add Kotlin image loading library to build.gradle (Module: app) (It also supports other images):

Gradle:

implementation 'io.coil-kt:coil:1.4.0'
implementation 'io.coil-kt:coil-svg:1.4.0'

or

Kts:

implementation("io.coil-kt:coil:1.4.0")
implementation("io.coil-kt:coil-svg:1.4.0")
  1. Add below extension function to any Kotlin file of your project, (outside of a class not inside of a class):

Here I used AppCompatImageView in xml, if you use only ImageView replace AppCompatImageView by ImageView from below function.

fun AppCompatImageView.loadSvgOrOther(myUrl: String?, cache: Boolean = true, errorImg: Int = R.drawable.logo_round // Place any error image from your drawable) {

myUrl?.let {
    if (it.lowercase().endsWith("svg")) {
        val imageLoader = ImageLoader.Builder(this.context)
            .componentRegistry {
                add(SvgDecoder([email protected]))
            }.build()

        val request = ImageRequest.Builder(this.context).apply {
            error(errorImg)
            placeholder(errorImg)
            data(it).decoder(SvgDecoder([email protected]))
        }.target(this).build()

        imageLoader.enqueue(request)
    } else {
        val imageLoader = ImageLoader(context)

        val request = ImageRequest.Builder(context).apply {
            if (cache) {
                memoryCachePolicy(CachePolicy.ENABLED)
            } else {
                memoryCachePolicy(CachePolicy.DISABLED)
            }
            error(errorImg)
            placeholder(errorImg)
            data("$it")
        }.target(this).build()

        imageLoader.enqueue(request)
    }
  }
} // loadSvgOrOther
  1. Now use like below:

    myAppCompatImageView.loadSvgOrOther("https[:]//example[.]com/image.svg")
    

Hope this will help, who wants to use Kotlin to load svg, png, jpg etc Images.

Upvotes: 8

Anubhav
Anubhav

Reputation: 2180

You can use Coil Image loading library,

Add the following dependencies to your app level build.gradle file,

def coilVersion = '1.2.2'
implementation "io.coil-kt:coil:$coilVersion"
implementation "io.coil-kt:coil-svg:$coilVersion"

Now create this method,

fun ImageView.loadImageFromUrl(imageUrl: String) {
val imageLoader = ImageLoader.Builder(this.context)
    .componentRegistry { add(SvgDecoder([email protected])) 
}
    .build()

val imageRequest = ImageRequest.Builder(this.context)
    .crossfade(true)
    .crossfade(300)
    .data(imageUrl)
    .target(
        onStart = {
            //set up an image loader or whatever you need
        },
        onSuccess = { result ->
            val bitmap = (result as BitmapDrawable).bitmap
            this.setImageBitmap(bitmap)
            //dismiss the loader if any
        },
        onError = {
            /**
             * TODO: set an error drawable
             */
        }
    )
    .build()

imageLoader.enqueue(imageRequest)

}

Now you can call this extension function from your ImageView,

imgView.loadImage(imageUrl)

This will work for svgs, pngs. I have not tried it with jpgs, but should work with them as well.

Upvotes: 0

Manthan Patel
Manthan Patel

Reputation: 1852

Load SVG using Glide V4 or above

Add dependencies in app.gradle > dependencies

implementation 'com.github.qoqa:glide-svg:2.0.4'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

Make new class SampleAppGlideModule.java and go to Build>Make Project(ctrl+f9)

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;

@GlideModule
public class SampleAppGlideModule extends AppGlideModule {



    @Override
    public boolean isManifestParsingEnabled() {
        return super.isManifestParsingEnabled();
    }

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);
        builder.setLogLevel(Log.DEBUG);
    }
}

Load SVG using Glide V4 or above

GlideApp.with(this)                      
.load(contentLangModels.get(i).getContentImage()).into(contentLangBinding.ivExtra);

Upvotes: 0

Itz Pkyadav
Itz Pkyadav

Reputation: 79

Hope the below code is useful for you.

  1. Add this dependency in build.gradle

    implementation 'com.github.corouteam:GlideToVectorYou:v2.0.0'

  2. Now start working in MainActivity.java

    ImageView image = (ImageView) findViewById(R.id.ivimage);

    String url= https://your_url/banking.svg GlideToVectorYou.init().with(this).load(Uri.parse(url),image);

Upvotes: 4

Ali Hasan
Ali Hasan

Reputation: 673

You can use this library

https://github.com/2coffees1team/GlideToVectorYou

As he say : "The library is based on Glide and offers the same functionalities + svg support".

Upvotes: 2

Ramesh sambu
Ramesh sambu

Reputation: 3539

Use this Glide based library loading xml

Add dependency

  compile 'com.github.ar-android:AndroidSvgLoader:1.0.0'

for latest android dependency Gradle use this instead

implementation 'com.github.ar-android:AndroidSvgLoader:1.0.0'

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivimage"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);            

        ImageView image = (ImageView) findViewById(R.id.ivimage);

        SvgLoader.pluck()
                .with(this)
                .setPlaceHolder(R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                .load("http://www.clker.com/cliparts/u/Z/2/b/a/6/android-toy-h.svg", image);

    }

    @Override protected void onDestroy() {
        super.onDestroy();
        SvgLoader.pluck().close();
    }
}

Upvotes: 11

Rags93
Rags93

Reputation: 1474

Update: For newer version please checkout the Glide Samples (https://github.com/bumptech/glide/tree/master/samples/svg)

-

You can use Glide (https://github.com/bumptech/glide/tree/v3.6.0) and AndroidSVG (https://bitbucket.org/paullebeau/androidsvg).

There is also a sample from Glide: https://github.com/bumptech/glide/tree/v3.6.0/samples/svg/src/main/java/com/bumptech/svgsample/app

Setup GenericRequestBuilder

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 uri = Uri.parse("https://de.wikipedia.org/wiki/Scalable_Vector_Graphics#/media/File:SVG_logo.svg");
            requestBuilder
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            // SVG cannot be serialized so it's not worth to cache it
                    .load(uri)
                    .into(mImageView);

Upvotes: 46

kandroidj
kandroidj

Reputation: 13932

Please refer to Having issue on Real Device using vector image in android. SVG-android

In the users post he asks a similar question and suggest he uses:

Create a member variable for the ImageView in your layout file;

private ImageView mImageView;

// intialize in onCreate(Bundle savedInstanceState)
mImageView = (ImageView) findViewById(R.id.image_view);

Download the image

private class HttpImageRequestTask extends AsyncTask<Void, Void, Drawable> {
    @Override
    protected Drawable doInBackground(Void... params) {
        try {


            final URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/e/e8/Svg_example3.svg");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            SVG svg = SVGParser. getSVGFromInputStream(inputStream);
            Drawable drawable = svg.createPictureDrawable();
            return drawable;
        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage(), e);
        }

        return null;
    }

    @Override
    protected void onPostExecute(Drawable drawable) {
        // Update the view
        updateImageView(drawable);
    }
}

Then Apply the drawable to the Imageview

@SuppressLint("NewApi")
private void updateImageView(Drawable drawable){
    if(drawable != null){

        // Try using your library and adding this layer type before switching your SVG parsing
        mImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mImageView.setImageDrawable(drawable);
    }
}

SVGParser is available at https://github.com/pents90/svg-android

Upvotes: 13

Related Questions