android developer
android developer

Reputation: 116332

Read and show WebP images

I know this question is already mentioned on some places (like here), but is there an easy way to read WebP images, like using a jar file?

It would be great to minimize the size of images of apps even on older devices.

Is it possible to read a WebP inputStream to a normal bitmap instance like you do with other formats, even on older android versions (older than ICS)?

Upvotes: 1

Views: 6166

Answers (2)

Golu
Golu

Reputation: 33

If your webp image is stored in assets folder then use this code to Read and show in imageView

try {
            InputStream inputStream = context.getAssets().open("yourfilename.webp");
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
            imageView.setImageBitmap(bmp);
           
        } catch (IOException e) {
            e.printStackTrace();
        }

Upvotes: 1

Krzysztof Kacprzak
Krzysztof Kacprzak

Reputation: 69

The example you hae provided is quite good, to summarise it you need to follow such steps:

  • download the webp library, current version here
  • create in your Android "jni" folder, copy libwep content to it
  • in jni/Android.mk add:

    swig/libwebp_java_wrap.c \

    to LOCAL_SRC_FILES := \ and removeinclude $(BUILD_STATIC_LIBRARY), put instead include $(BUILD_SHARED_LIBRARY)

  • go to your project directory and run

    ./path-to-android-ndk/ndk-build

  • if you don't know how to use ndk, try here

  • if you compile successfuly, you obtain libwebp.jar, include it in your project build path

  • in you activity, you put firstly:

    static { System.loadLibrary("webp"); }

  • then you can read .webp file by InputStream (i.e. from assets folder):

    InputStream is = getAssets().open("image.webp");

  • download apache library from here, include it in your project build path

  • then you can read InputStream to byte array:

    byte[] encoded = IOUtils.toByteArray(is);

  • decode the file by libwebp:

    int[] width = new int[] { 0 };

    int[] height = new int[] { 0 };

    byte[] decoded = libwebp.WebPDecodeARGB(encoded, encoded.length, width, height);

  • convert to bitmap:

    int[] pixels = new int[decoded.length / 4];

    ByteBuffer.wrap(decoded).asIntBuffer().get(pixels);

    Bitmap bitamp = Bitmap.createBitmap(pixels, width[0], height[0], Bitmap.Config.ARGB_8888);

  • last lines taken form here

  • do with your bitmap whatever you want.

Upvotes: 1

Related Questions