We are about to switch to a new forum software. Until then we have removed the registration on this forum.
How can i make the below code work?
PImage img;
String str;
str = "img";
image(str,100,100);
I have the PImage name in the string but I don't know how to convert it.
Answers
what's wrong with using
image(img, 100, 100);
? what are you trying to do? why do you need this extra layer of abstraction?I assume you have many images and you want to display one of them based on the contents of some string. For example:
Right?
Well there are two and a half ways you can do this. The first is to use conditional statements:
This approach is direct and clear, but does not scale well (imagine you have hundreds or thousands of possible images to pick from).
The half-a-solution way is to use the string as part of the filename that you use when you load the image.
This works great, and scales well, but the catch is that you will need to know which image you want to load ahead of time. Still, this is worth mentioning (it might be okay if the image is one picked at random, for example).
Finally, the BEST solution is to use an ARRAY. Instead of having each of your images stored in different PImage variables, just store them all in one ARRAY of Pimages, and then use the String to determine the index into that array. Example:
Notice that this involves using a separate
lookup
array that matches each possible name (like "dog" or "pig" or whatever) with a given INDEXi
. That is, the "pig" image is the first (0th) one in theimg_animal
array becauselookup[0]
is "pig".Also, realize that if your
lookup
array contains the filenames, then you could write a loop to load all these images too (instead of loading them one per line). Fixing this is left as an exercise for the reader...GoToLoop, are you okay? Your passion is just, like, gone. I mean, dude.
Just want to mention HashMap, can connect String to image - but again you need to load the HashMap with content first
Oh so I can do:
img = loadImage(str + ".png");
Thanks!
@RockyHawk --
You can, and I also want to strongly emphasize this works best for setup or a one-time loader function: do not call loadImage() in draw(). Most of the the time this is a mistake -- and a terrible performance hit.
Calling loadImage every time an image is needed in a running sketch is solving "how do I choose between different cereals for breakfast?" is "order a new cereal box from Amazon every time you feel hungry, then sit and wait until it arrives." It works, but now you sitting at the breakfast table for two days waiting for your cereal -- and you only eat breakfast every two days.