Load PNGs from assets using Android NDK

Many developers appear to embed libpng with their NDK project in order to decode PNGs. While libpng does offer great flexibility, the amount of code necessary to decode an image is surprisingly high, and the additional work needed to maintain a libpng build means that most of the time, using the system’s decoding routines is perfectly reasonable.

But wait, isn’t the NDK for C++ development only? True, but usually we are still running in a virtual machine that has access to a large panel of high-level utility libraries. This article actually demonstrates a broader, useful technique I call return-to-JVM that you can use for other purposes than simply PNG loading.

I suggest putting your PNG files in the assets directory of your application, so that they can be accessed by path.

First, let’s decide of a Java class and object that will act as a PNG factory and manager for us. Let’s call it PngManager:

import android.content.res.AssetManager;

public class PngManager
{
    private AssetManager amgr;

    public Bitmap open(String path)
    {
        try
        {
            return BitmapFactory.decodeStream(amgr.open(path));
        }
        catch (Exception e) { }
        return null;
    }

    public int getWidth(Bitmap bmp) { return bmp.getWidth(); }
    public int getHeight(Bitmap bmp) { return bmp.getHeight(); }

    public void getPixels(Bitmap bmp, int[] pixels)
    {
        int w = bmp.getWidth();
        int h = bmp.getHeight();
        bmp.getPixels(pixels, 0, w, 0, 0, w, h);
    }

    public void close(Bitmap bmp)
    {
        bmp.recycle();
    }
}

Now to load the PNG from the C++ part of the program, use the following code:

jobject g_pngmgr;
JNIEnv *g_env;

/* ... */

char const *path = "images/myimage.png";

jclass cls = g_env->GetObjectClass(g_pngmgr);
jmethodID mid;

/* Ask the PNG manager for a bitmap */
mid = g_env->GetMethodID(cls, "open",
                         "(Ljava/lang/String;)Landroid/graphics/Bitmap;");
jstring name = g_env->NewStringUTF(path);
jobject png = g_env->CallObjectMethod(g_pngmgr, mid, name);
g_env->DeleteLocalRef(name);
g_env->NewGlobalRef(png);

/* Get image dimensions */
mid = g_env->GetMethodID(cls, "getWidth", "(Landroid/graphics/Bitmap;)I");
int width = g_env->CallIntMethod(g_pngmgr, mid, png);
mid = g_env->GetMethodID(cls, "getHeight", "(Landroid/graphics/Bitmap;)I");
int height = g_env->CallIntMethod(g_pngmgr, mid, png);

/* Get pixels */
jintArray array = g_env->NewIntArray(width * height);
g_env->NewGlobalRef(array);
mid = g_env->GetMethodID(cls, "getPixels", "(Landroid/graphics/Bitmap;[I)V");
g_env->CallVoidMethod(g_pngmgr, mid, png, array);

jint *pixels = g_env->GetIntArrayElements(array, 0);

Now do anything you want with the pixels, for instance bind them to a texture.

And to release the bitmap when finished:

g_env->ReleaseIntArrayElements(array, pixels, 0);
g_env->DeleteGlobalRef(array);

/* Free image */
mid = g_env->GetMethodID(cls, "close", "(Landroid/graphics/Bitmap;)V");
g_env->CallVoidMethod(g_pngmgr, mid, png);
g_env->DeleteGlobalRef(png);

This will not work out of the box. There are a few last things to do, which will hugely depend on your global application architecture and are thus left as an exercise to the reader:

  • Store an AssetManager object in PngManager::amgr before the first call to open() is made (for instance by calling Activity::getAssets() upon application initialisation).
  • Store in g_env a valid JNIEnv * value (the JNI environment is the first argument to all JNI methods), either by remembering it or by using jvm->AttachCurrentThread().
  • Store in g_pngmgr a valid jobject handle to a PngManager instance (for instance by calling a JNI method with the instance as an argument).
  • Error checking was totally omitted from the code for the sake of clarity.
  • Some of the dynamically retrieved variables could benefit from being cached.

I hope this can prove helpful!

For a C++-only solution to this problem, see Load pngs from assets in NDK by Bill Hsu.

  • Posted: 2011-03-02 04:02 (Updated: 2011-03-04 14:52)
  • Author: sam
  • Categories: android code tip

Comments

1. pablolupo@gmail.com -- 2011-08-12 16:11

Hi Sam, before nothing thank you so much for writing this article and I'm sorry for my english :)

I'm having troubles when I try to call my native function passing my PngManager instance as an argument. The c++ function prototype is this:

JNIEXPORT void JNICALL Java_com_ndkpackage_ndkproject_GameRenderer_nativeInit(JNIEnv* env, jclass cls, jobject* pngManager)

Java declaration: private static native void nativeInit(Object pngLoader);

At Run-time I have this error on LogCat: WARN/dalvikvm(254): No implementation found for native Lcom/ndkpackage/ndkproject/GameRenderer;.nativeInit (Lcom/ndkpackage/ndkproject/PngLoader;)V

Could you help me with this? Thanks in advance. Lupo

4. anonymous -- 2011-08-14 00:19

Fixed. Just send an instance of the PngManager from Java and received it as an jobject pointer as I said before, but I forget to modify the c++ native function prototype... Sorry.

Anyway, I still having problems at this line:

jobject png = g_env->CallObjectMethod(g_pngmgr, mid, name);

png always is null. Any sugestion? Thanks. Lupo

5. sam -- 2011-08-14 10:09

@Lupo: if png is null and there was no crash, it means the open() method was properly called, but it failed for some reason. You will have to hook some error reporting in open(), right here:

           return BitmapFactory.decodeStream(amgr.open(path));
        }
        catch (Exception e) { /* error reporting goes here */ }
        return null;
    }
6. anonymous -- 2012-06-11 10:40

I am wondering if it is possible to load the bitmap as a texture into openGL in the java and have it then available to use in NDK openGL?

7. moggiozzi -- 2012-08-21 20:53

Hi Sam. I try do it with native-activity project in ndk samples. I add package myapp.mypack and add to package PngManager class. But when i try get jclass for PngManager in android_main function i get NULL. My code:

void android_main(struct android_app* state) {
	env = state->activity->env;
	jvm = state->activity->vm;
	jvm->AttachCurrentThread(&env, NULL);
	jclass fileClass = env->FindClass("myapp/mypack/PngManager");
	if(fileClass==NULL)
		LOGI("fileClass is NULL");

If I'm trying to, for example, "java/io/File", I get non-null pointer. It would be nice if you suggested solution.

8. ZeDuS -- 2013-09-02 20:11

"I am wondering if it is possible to load the bitmap as a texture into openGL in the java and have it then available to use in NDK openGL? "

Of course you can, since textures in GLES (1/2) are basically just IDs, you can pass them as int back to native code. I've managed to do it with a "special" texture (camera preview) and I'm sure it's possible with "simple" textures.

9. titmouse001@gmail.com -- 2015-05-14 00:21

Thanks - works like a dream. One small thing... Don't forget to clean up that cls instance as a last call, it's possible to run out of refs after about 512 calls. env->DeleteLocalRef( cls);

This link talks about how to make it global rather than calling the above delete each time... http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/refs.html

10. anonymous -- 2016-09-13 08:25

Hi,

Thank you for the awesome tutorial. I am having problems with applying this method to multiple bitmap files though. I keep getting dvmHeapBitmapScanWalk(HeapBitmap*, void (*)(Object*, void*, void*), void*) error.

I wonder if you can provide an example of loading multiple files.

Cheers

185. BernardBax -- 2016-10-20 21:55

Essay on best teacher http://www.thegreatnewsinc.com/Critical-Thinking-Paper - Critical Thinking Paper, Buy research papers Best essay review services http://youngwillstone.com/edit-college-essays-online - Edit college essays online, Academic report writing Essay writing courses http://verybestphotos.com/statics-homework-help - Statics homework help, College paper writing Need help for doing my assignment http://www.thegreatnewsinc.com/write-my-paper-write-my-paper-for-$10-or-less - Write my paper write my paper for $10 or less, Writing lab reports Easiest way to write an essay http://verybestphotos.com/need-help-writing-a-essay - Need help writing a essay, English homework help

271. subanal -- 2016-11-27 00:43

raK4GL There is visibly a bunch to realize about this. I believe you made certain nice points in features also.

368. useful source -- 2017-01-31 18:23

ER8FcF Thanks a lot for the article. Keep writing.

369. that site -- 2017-02-01 00:33

8uEuaG written. In my opinion, it might bring your website a little bit more interesting.

370. anonymous -- 2018-01-16 07:57

What a good post. I have very good knowledge about the Java. You have shared very good post with us and shared very good points which practically makes it work. To get trolley wheels Click here http://uktrolleywheels.uk/

371. roblox hack -- 2018-01-25 09:18

hello friend.I found A lot of interesting information here. <a href="http://freerobux.spruz.com/">roblox hack</a>.i have agreed this website is very nice just us the app thanks for sharing it.

372. Jennings -- 2018-03-18 05:43

This is indeed a very useful tutorial. I really like it. For Android, you can get the movie hd apk latest version. Download the movies hd apk 2018 variant for smartphones. Install updated apk film hd version and enjoy hd movies. After that, it is easy to have movies apk on your device. Thank you for this informative guide. Keep going.

373. anonymous -- 2018-03-20 13:32

Get expert Question & Answer Dumps PDF Online. We Provide latest IT Certification HPE0-S51 Exams PDF for preparation Study Guide Test Practice for Success in exams. This is an online education portal

374. anonymous -- 2018-03-26 20:43

The new version of android NDK is not allowing the old data of PNG to store in it, it is showing error message while trying to upload the data into it. I even checked in their http://best-essay-writing-service.reviews blog site if I can get any tutorial or patch file regarding this failure in app.

375. anonymous -- 2018-05-17 18:07

Michael M.Calbertis the chairman and Todd Vasos is the CEO of the company. The Dollar General provides us with clothing, Cleaning Supplies, Home Decors, Health and Beauty, Aids, Pet Supplies, Toys, Seasonal Items and Grocery. Dollar General gave the wonderful opportunity called http://dgcustomerfirstcom.info/dgcustomerfirst/.

376. anonymous -- 2018-05-21 13:24

If you are looking best sources and study material of MB6-896

dumps to prepare and pass all exams, I advised visiting the best platform certificationssoul. Try out https://www.certificationssoul.com/microsoft/mb6-896-exam-questions.html

377. RichardTDavidson -- 2018-06-05 08:31

HTTP Injector APK Download https://httpinjector.co/

378. anonymous -- 2018-06-16 19:09

whatsapp mods like whatsapp plus , gbwhatsapp, yowhatsapp and ogwhatsapp on apk trendz : https://www.apktrendz.co

379. anonymous -- 2018-07-05 11:09

Hello guys do you know that going through a review of websites will give you much insight about it which you can’t know by simply visiting it,Here is the allassignmenthelp.com Reviews that reviews the website and provides you the best website . http://assignmentshelpreview.com/allassignmenthelp-com-reviews/

380. Assignment help -- 2018-07-10 08:28

Some students are suffering from distress, whereas some suffer from eustress in life. Low scores in academics, examination, pent-up assignments or other academic issues can stress out the students. To resolve such type of problems, they can take assignment help from the online services at their last minute. Getting help from these services are beneficial as they provide quality work in quick time. Therefore you can have a hike in your grades quite easily. https://www.allassignmenthelp.com/java-assignment-help.html https://www.allassignmenthelp.com/computer-programming-assignment-help.html

381. Marketing Research Homework Help -- 2018-07-13 12:44

Dissertation Guidance Provides Quality Online Dissertation Help For Students. http://themarketingresearch.com

382. PM Assignment Help -- 2018-07-13 13:44

Only Professional Writers Can Make This Kind Of Material, Cheers http://projectmanagementhelp.net

383. anonymous -- 2018-07-16 18:22

Macy’s is one of the largest stores that mainly operates in the United States. It has a web portal for its employees which is named ‘Macys Insite – Employee Connection’. It is specially designed for the employees who are working at Macy’s. https://myinsite.info/

384. mancakessuch -- 2018-09-04 12:26

But wait, isn’t the NDK for C++ development only? True, but usually we are still running in a virtual machine that has access to a large panel of high-level utility libraries. This article actually demonstrates a broader, useful technique I call return-to-JVM that you can use for other purposes than simply PNG loading.

https://happywheels3d.com/

385. Text Chemistry -- 2018-09-22 18:16

I think I have never seen such blogs ever before that has complete things with all details which I want. So kindly update this ever for us. Text Chemistry

386. Snoring -- 2018-09-22 18:45

It is perfect time to make some plans for the future and it is time to be happy. I've read this post and if I could I desire to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it! Snoring

387. Stomach Ache -- 2018-09-22 18:45

You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!! Stomach Ache

388. anonymous -- 2018-09-22 18:47

The writer is enthusiastic about purchasing wooden furniture on the web and his exploration about best wooden furniture has brought about the arrangement of this article. Gout

389. anonymous -- 2018-09-22 18:49

You actually make it look so easy with your performance but I find this matter to be actually something which I think I would never comprehend. It seems too complicated and extremely broad for me. I'm looking forward for your next post, I’ll try to get the hang of it! Low Carb Foods

390. anonymous -- 2018-09-22 18:51

They're produced by the very best degree developers who will be distinguished for your polo dress creating. You'll find polo Ron Lauren inside exclusive array which include particular classes for men, women. Boost Your Blood Levels

391. anonymous -- 2018-09-22 18:53

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well.. Lower Your Cholesterol Levels

392. anonymous -- 2018-09-22 18:54

This is a fantastic website , thanks for sharing. Blood Clot

393. anonymous -- 2018-09-24 04:08

Happy Wheels Racing games - https://happywheels24.com

394. aber -- 2018-10-10 07:51

Even though the coding is very confusing, it's fun to deal with. http://www.unblockedgames6.com

395. anonymous -- 2018-10-14 10:01

Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. acquariologia http://www.massimograndeacquari.it/

396. anonymous -- 2018-10-16 13:05

This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it Enjoy Mexico Villa Rentals https://enjoymexico.net/villa-rentals/

397. anonymous -- 2018-10-17 13:35

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information... Enjoy Mexico Villa Rentals in Punta Mita https://enjoymexico.net/punta-mita-villa-rentals/

398. anonymous -- 2018-10-20 15:40

The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. <a href="http://whistlergrandofficial.doodlekit.com/">Whistler Grand</a>

399. anonymous -- 2018-10-30 13:51

Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites! Church on the hill mcminnville

400. anonymous -- 2018-10-31 12:25

Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! Bonrollen kaufen http://kassenrollen2.spruz.com/

401. anonymous -- 2018-11-01 07:53

Law assignment help in understanding how legal theories and concepts can be enforced in the real world. It seeks to guide us about prospective-reform on the laws across courts, policing, businesses, legal firms, and security agencies.

Visit us: -

https://www.myassignmentservices.com/ https://www.myassignmentservices.com/law-assignment-service.html

402. anonymous -- 2018-11-01 14:00

The information you have posted is very useful. The sites you have referred was good. Thanks for sharing... hdmi encoder https://www.provideoinstruments.com/IPTV-Streaming_c_39.html

403. anonymous -- 2018-11-05 12:19

Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! Will Grundy http://willgrundyrealestate.com

404. anonymous -- 2018-11-06 11:55

The information you have posted is very useful. The sites you have referred was good. Thanks for sharing... Vertz Marketing https://vertzmarketing.com

405. anonymous -- 2018-11-08 13:49

Excellent information on your blog, thank you for taking the time to share with us. Amazing insight you have on this, it's nice to find a website that details so much information about different artists. Florida Tax Lawyers http://floridataxlawyers.net

406. anonymous -- 2018-11-11 14:00

Whatsapp 2019 later will appear soon as a Whatsapp version is the latest. As the development time Whatsapp is always correcting its performance. So that users more easily apply it. Apply the Whatsapp version update will certainly be more profitable users.Some of the reasons people love the application Whatsapp is because of the features provided by this one application.

http://www.whatsapp2019.net/

407. anonymous -- 2018-11-12 17:06

Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject! jual cctv http://www.lumbatech.com/

408. anonymous -- 2018-11-13 12:38

I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day! immo https://wirtschaft.com/immobilien

409. Amelia -- 2018-11-15 10:50

Thank you so much for this useful info. http://www.unblockedgamesmania.com

410. raman -- 2018-11-17 08:45

GBWhatsapp apk Download Latest Version 2018. Download Latest GB Whatsapp for Use 2 Whatsapp in One Mobile. <a href="http://appgbdownload.com/">GBWhatsApp App</a> . http://appgbdownload.com

411. mjjones733@gmail.com -- 2018-11-17 11:29

If you are still in a dilemma, you could ask your teacher for some guidance, or you can take Assignment helpfrom different assignment writing service providers. There you can find many online experts, who are all set to help you in your assignment. The proper outline followed by them will give you an idea of how to make your assignment look more presentable and attractive. https://www.allassignmenthelp.com

412. anonymous -- 2018-11-17 15:14

I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. Arbeit https://wirtschaft.com/jobboerse

413. maxdroid -- 2018-11-18 11:39

I love android phone, you can find many attractive games on my website. https://maxdroid.net/

414. anonymous -- 2018-11-23 08:49

How am I able to bring together a simple software the use of Android NDK? I am used to using gcc, I would like to compile a program to use on my tablet, I even have compiled a software using the https://www.trueassignmenthelp.co.uk/ C4droid compiler and I have established it the usage of a terminal emulator. I need to do the identical however i need to compile the binary using my mac and android NDK.

415. anonymous -- 2018-11-25 12:30

This blog is so nice to me. I will keep on coming here again and again. Visit my link as well.. see this https://helpwithmystudentloan.com/

416. Metal fence Gates -- 2018-11-27 20:34

We make and deliver the best in custom gates, From ornamental gates to barrier gates we make them and deliver them quickly. We have or own custom welding shop and do all the work ourselves. We love what we do and so will you, call us for a free quote on any type of metal gates. Custom made wrought iron gates from our custom Shop. We deliver you small or large decorative garden gates to very large custom double driveway gates. You dream it we will build it, we make Amazing Gate. Metal fence Gates

417. anonymous -- 2018-12-01 17:28

Downloaf shell shockers full version.

418. Robert -- 2018-12-01 18:48

hank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! kyocera inkjet printheads

419. anonymous -- 2018-12-02 09:13

At L.S Fencing & Metal Work . We are a family owned and operated fencing company with years of experience and top notch quality.Our customers are our number one priority and we go above and beyond to make sure they are satisfied. There is no job too big or too small. We are a fully licensed and insured company with many references and are happy to stand by our one year warranty on all parts and labor. We have the equipment and know how to do the job right the first time. Abbotsford Chain link Fencing

420. anonymous -- 2018-12-02 10:02

Looking for custom product packaging? https://www.customdeluxeboxes.com/ offers quality custom product boxes in USA and Canada. Get printed boxes no minimum with free shipping and design support. Choosing the right custom product packaging design gives you an edge over your competitors. This is why investing in product packaging and design elements can be worth spending every penny.

421. anonymous -- 2018-12-08 09:53

Excellent information on your blog, thank you for taking the time to share with us. Amazing insight you have on this, it's nice to find a website that details so much information about different artists. Mark Statts http://www.markstatts.com/

422. anonymous -- 2018-12-10 15:31

Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post. Kevenides Law https://kevenideslaw.com/

423. anonymous -- 2018-12-11 04:47

This is a good article. This post provides real quality information. I will definitely look at it. Really helpful tips are provided here. thank you very much. Keep up the good work. read more :https://hotmailsignaz.com/delete-microsoft-account/

Add New Comment