Must be a way looping through this code:
private void loadSprites() {
this.sprites[0] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom01);
this.sprites[1] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom02);
this.sprites[2] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom03);
this.sprites[3] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom04);
this.sprites[4] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom05);
this.sprites[5] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom06);
this.sprites[6] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom07);
}
Thanks!
If I am understand your question, you want something like,
int[] drawables = {R.drawable.ic_boom01,R.drawable.ic_boom02,R.drawable.ic_boom03,R.drawable.ic_boom04,R.drawable.ic_boom05,R.drawable.ic_boom06,R.drawable.ic_boom07}
private void loadSprites() {
for(int i=0; i<this.sprites.length; i++)
this.sprites[i] = BitmapFactory.decodeResource(getResources(), drawables[i]);
}
You should place your images in the assets folder. From their you can access them via their file name. See http://developer.android.com/reference/android/content/res/AssetManager.html.
Please look at below code for that.
First make int array
int[] mImgArray = { R.drawable.ic_boom01, R.drawable.ic_boom02,
R.drawable.ic_boom03, R.drawable.ic_boom04, R.drawable.ic_boom05,
R.drawable.ic_boom06, R.drawable.ic_boom07 };
or Set this Image to ImageView using below code
mImgView1.setImageResource(mImgArray[0]);
And you can convert this image directly to bitmap and store into bitmap array using below code.
Bitmap mBmpArray=new Bitmap[mImgArray.length];
for(int i=0; i<mImgArray.length; i++)
mBmpArray[i] = BitmapFactory.decodeResource(getResources(), mImgArray[i]);
}
This works for me
//Bitmap of images for fly asset
private Bitmap fly[] = new Bitmap[8];
//Initialize array of images
for(int i = 0; i < fly.length; i++){
this.fly[i] = BitmapFactory.decodeResource( getResources(), getResources().getIdentifier("fly_frame" + i, "drawable", context.getPackageName() ) );
}
You can do that in a simple for loop.. and start from the first id and increment it by 1 at each loop.. though I don't recommend you to do this..
Related
I have an array which contains several drawables needed by my main java code I use this to call them when needed:
mImagesArray = new int[]{R.drawable.img_0, R.drawable.img_1, R.drawable.img_2,...,R.drawable.img_m}
this direct implementation method works but imagine if i have an array containing +100 images, I would call each drawable value from img_1 to the final img_100 which is pretty frustrating.
What I need is a function which use an increment int i value that is defined by (for i=0;i<m;i++) so this function would look much simpler than the previous one that I used.. something like mImagesArray = new int[]{R.drawable.img_i} maybe ?
I hope you understood my question, basically I want an all-set function which requires only mImagesArray's number of elements..
edit ** mImagesArray is used in:
private void drawImage(Canvas canvas) {
//Get the image and resize it
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray_ar[mImagesArrayIndex]);
//Draw background
// customWallpaperHelper.setBackground(canvas);
//Scale the canvas
PointF mScale = customWallpaperHelper.getCanvasScale(mImageScale, image.getWidth(), image.getHeight());
canvas.scale(mScale.x, mScale.y);
//Draw the image on screen
Point mPos = customWallpaperHelper.getImagePos(mScale, image.getWidth(), image.getHeight());
canvas.drawBitmap(image, mPos.x, mPos.y, null);
}
THANKS.
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
And use it like this:
int myID =
getResourceID("your_resource_name", "drawable", getApplicationContext());
Note: no path nor extension, in case of images.
You can even not use the mImagesArray array: just use int myID = getResourceID("img_" + i, "drawable", getApplicationContext());, where i is an integer (the same integer you would use as your array index).
Like this:
Bitmap image =
BitmapFactory.decodeResource(getResources(),
getResourceID("img_" + mImagesArrayIndex, "drawable", getApplicationContext()));
I would rather suggest you to just create a string array with all the drawable names and then extract the drawable from the names.
I mean to say similar to this:-
String[] drawables=new String[100]
for(int i=0;i<100;i++)
drawables[i]="img"+i;
Then finally when you want it you get by name like this:-
int drawableResourceId = this.getResources().getIdentifier(drawables[i], "drawable", this.getPackageName());
Had the same problem.
int x,i=0;
While(i<100){
ImageView view = new ImageView(this);
name="img_"+i;
x=getResources().getIdentifier(name, "drawable, getPackageName());
view.setImageResurse(x);
mainActivity.addView(view);
i++;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
*Update - solved**
What I was looking for was how to get the Resource ID. It's difficult to formulate a question when you don't know what you don't know, but the two guys that answered it within a matter of minutes seemed to understand. Thanks, guys.
Here is the code I was finally able to use without having to load all 32 bitmaps while using a String to identify which specific one I was after.
StartCalc session = new StartCalc(context);
int findDate = session.findDate();
for (int i = 0; i < daysTil.length; i++) {
String numbers = "numbers" + i;
int resId = getResources().getIdentifier(numbers, "drawable", getPackageName());
if (i == findDate) {
ivNumbers.setImageBitmap(BitmapFactory.decodeResource(getResources(), resId));
}
}
*Original question**
I'm trying to use a for loop to fill an array of Bitmaps, from 0 to 32, but I can't figure out how to use the String "numbers" (identified on line 3) to populate the address required by the BitmapFactory (referenced on line 5). Here's the code of me filling the array two ways. The long way has issues taking up too much memory, and since I only need one of these images based on the date, I'm hoping there's a way to do this.
private void setNumbers() {
for (int i = 0; i < 33; i++) {
String numbers = "R.drawable.numbers" + i;
Log.e(TAG, numbers);
daysTil[i] = BitmapFactory.decodeResource(getResources(), numbers);
}
daysTil[0] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers0);
daysTil[1] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers1);
daysTil[2] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers2);
daysTil[3] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers3);
daysTil[4] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers4);
daysTil[5] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers5);
daysTil[6] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers6);
daysTil[7] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers7);
daysTil[8] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers8);
daysTil[9] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers9);
daysTil[10] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers10);
daysTil[11] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers11);
daysTil[12] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers12);
daysTil[13] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers13);
daysTil[14] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers14);
daysTil[15] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers15);
daysTil[16] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers16);
daysTil[17] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers17);
daysTil[18] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers18);
daysTil[19] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers19);
daysTil[20] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers20);
daysTil[21] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers21);
daysTil[22] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers22);
daysTil[23] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers23);
daysTil[24] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers24);
daysTil[25] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers25);
daysTil[26] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers26);
daysTil[27] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers27);
daysTil[28] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers28);
daysTil[29] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers29);
daysTil[30] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers30);
daysTil[31] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers31);
daysTil[32] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers32);
}
You should use this method to find the resource id of the drawable:
String numbers = "numbers" + i;
int resId = getResources().getIdentifier(numbers, "drawable", getPackageName());
Reference: getIdentifier
The Resources class has this method:
public int getIdentifier (String name, String defType, String defPackage)
So the complete statement could look somewhat like this:
for (int i = 0; i < 33; i++) {
String numbers = "R.drawable.numbers" + i;
Log.e(TAG, numbers);
Resources resources = <context>.getResources();
daysTil[i] = BitmapFactory.decodeResource(getResources(),
resources.getIdentifier ("numbers" +i, "drawable",
<context>.getPackageName());
}
(note: this code is untested - it's just for demonstration)
I am trying to fetch an image from a URL into a Bitmap and then using the raw data from the Bitmap am trying to create a CCSprite. The issue here is that the image is corrupted when I display the sprite. I created a standalone android only application(no cocos2dx) and used the same code to fetch and display the Bitmap and its displayed correctly. Any reason why the image is not being properly rendered in cocos2dx?
My code to fetch the image from the URL is:
String urlString = "http://www.mathewingram.com/work/wp-content/themes/thesis/rotator/335f69c5de_small.jpg";//http://graph.facebook.com/"+user.getId()+"/picture?type=large";
Bitmap pic = null;
pic = BitmapFactory.decodeStream((InputStream) new URL(urlString).getContent());
int[] pixels = new int[pic.getWidth() * pic.getHeight()];
pic.getPixels(pixels, 0, pic.getWidth(), 0, 0,pic.getWidth(),pic.getHeight());
int len = pic.getWidth()* pic.getHeight();
nativeFbUserName(pixels,len,pic.getWidth(), pic.getHeight());
The function "nativeFbUserName" is a call to a native c++ function which is :
void Java_com_WBS_Test0001_Test0001_nativeFbUserName(JNIEnv *env, jobject thiz,jintArray name, jint len, jint width, jint height) {
jint *jArr = env->GetIntArrayElements(name,NULL);
int username[len];
for (int i=0; i<len; i++){
username[i] = (int)jArr[i];
}
HelloWorld::getShared()->picLen = (int)len;
HelloWorld::getShared()->picHeight = (int)height;
HelloWorld::getShared()->picWidth = (int)width;
HelloWorld::getShared()->saveArray(username);
HelloWorld::getShared()->schedule(SEL_SCHEDULE(&HelloWorld::addSprite),0.1);
}
void HelloWorld::saveArray(int *arrayToSave)
{
arr = new int[picLen];
for(int i = 0; i < picLen; i++){
arr[i] = arrayToSave[i];
}
}
void HelloWorld::addSprite(float time)
{
this->unschedule(SEL_SCHEDULE(&HelloWorld::addSprite));
CCTexture2D *tex = new CCTexture2D();
bool val = tex->initWithData(arr,(cocos2d::CCTexture2DPixelFormat)0,picWidth,picHeight, CCSizeMake(picWidth,picHeight));
CCLog("flag is %d",val);
CCSprite *spriteToAdd = CCSprite::createWithTexture(tex);
spriteToAdd->setPosition(ccp(500, 300));
this->addChild(spriteToAdd);
}
Edit:
So I found this link Access to raw data in ARGB_8888 Android Bitmap that states that it might be a bug. Has anyone found a solution to this?
EDIT
So I just noticed a corruption of images on the lower right corner of the image.I am not sure why this is happening and how to fix it. Any ideas?
EDIT END
Answering my own question, I obtained a byte array from the bitmap using:
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
And then passed this byte array to the native code.
I need to add an image into "item". item is an xml file with TextView...
item = new ArrayList<String>();
item.add("an image");
Try this code
ArrayList<Bitmap> mBit = new ArrayList<Bitmap>(9);
for (int i = 0; i < 9; i++)
{
mBit.add(Bitmap.createBitmap(bitmapOrg, (i % 3) * newWidth, (i / 3) * newHeight, newWidth, newHeight));
}
Collections.shuffle(mBit);
for (int i = 0; i < 10; i++)
{
Bitmap bitmap = mBit.get(i));
//Do something here
}
You should create an ArrayList of objects and you can put everything you want in it and manipulate like this :
ArrayList<Object> array = new ArrayList<Object>();
array.put(0,"A string");
array.put(1,yourbitmap);
String string = (String) array.get(0);
Bitmap bitmap = (Bitmap) array.get(1);
You must cast when you get get because it is an object array.
If by image, you mean an image File and not Image object. Then use
add(fileObject.toString())
and while retrieving recreate File object using that object String.
new File(array.get(0)).getPath()
I have two png image files that I would like my android app to combine programmatically into one png image file and am wondering if it is possible to do so? if so, what I would like to do is just overlay them on each other to create one file.
the idea behind this is that I have a handful of png files, some with a portion of the image on the left with the rest transparent and the others with an image on the right and the rest transparent. and based on user input it will combine the two to make one file to display. (and i cant just display the two images side by side, they need to be one file)
is this possible to do programmatically in android and how so?
I've been trying to figure this out for a little while now.
Here's (essentially) the code I used to make it work.
// Get your images from their files
Bitmap bottomImage = BitmapFactory.decodeFile("myFirstPNG.png");
Bitmap topImage = BitmapFactory.decodeFile("myOtherPNG.png");
// As described by Steve Pomeroy in a previous comment,
// use the canvas to combine them.
// Start with the first in the constructor..
Canvas comboImage = new Canvas(bottomImage);
// Then draw the second on top of that
comboImage.drawBitmap(topImage, 0f, 0f, null);
// comboImage is now a composite of the two.
// To write the file out to the SDCard:
OutputStream os = null;
try {
os = new FileOutputStream("/sdcard/DCIM/Camera/" + "myNewFileName.png");
comboImage.compress(CompressFormat.PNG, 50, os)
} catch(IOException e) {
e.printStackTrace();
}
EDIT :
there was a typo,
So, I've changed
image.compress(CompressFormat.PNG, 50, os)
to
bottomImage.compress(CompressFormat.PNG, 50, os)
You can do blending. This is not particular to Android. It's just universal image processing.
EDIT:
You may find these articles & samples & code useful:
http://www.jhlabs.com/ip/
http://kfb-android.blogspot.com/2009/04/image-processing-in-android.html
http://code.google.com/p/jjil/
Image Processing on Android
I use this code
private class PhotoComposition extends AsyncTask<Object, Void, Boolean> {
private String pathSave;//path save combined images
#Override
protected Boolean doInBackground(Object... objects) {
List<String> images = (List<String>) objects[0]; //lsit of path iamges
pathSave = (String) objects[1];//path save combined images
if (images.size() == 0) {
return false;
}
List<Bitmap> bitmaps = new ArrayList<>();
for (int i = 0; i < images.size(); i++) {
bitmaps.add(BitmapFactory.decodeFile( images.get(i)));
}
int width = findWidth(bitmaps);//Find the width of the composite image
int height = findMaxHeight(bitmaps);//Find the height of the composite image
Bitmap combineBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);//create bitmap of composite image
combineBitmap.eraseColor(Color.parseColor("#00000000")); //bcakgraound color of composite image
Bitmap mutableCombineBitmap = combineBitmap.copy(Bitmap.Config.ARGB_8888, true);//create mutable bitmap to create canvas
Canvas canvas = new Canvas(mutableCombineBitmap);// create canvas to add bitmaps
float left = 0f;
for (int i = 0; i < bitmaps.size(); i++) {
canvas.drawBitmap(bitmaps.get(i), left, 0f, null);//Taking photos horizontally
left += bitmaps.get(i).getWidth();//Take right to the size of the previous photo
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(pathSave);//path of save composite image
mutableCombineBitmap.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean isSave) {
if (isSave) {
//iamge save on pathSave
Log.i("PhotoComposition", "onPostExecute: " + pathSave);
}
super.onPostExecute(isSave);
}
private int findMaxHeight(List<Bitmap> bitmaps) {
int maxHeight = Integer.MIN_VALUE;
for (int i = 0; i < bitmaps.size(); i++) {
if (bitmaps.get(i).getHeight() > maxHeight) {
maxHeight = bitmaps.get(i).getHeight();
}
}
return maxHeight;
}
private int findWidth(List<Bitmap> bitmaps) {
int width = 0;
for (int i = 0; i < bitmaps.size(); i++) {
width += bitmaps.get(i).getWidth();
}
return width;
}
USAGE
List<String> images = new ArrayList<>();
images.add("/storage/emulated/0/imageOne.png");//path of image in storage
images.add("/storage/emulated/0/imageTwo.png");
// images.add("/storage/emulated/0/imageThree");
// ... //add more images
String pathSaveCombinedImage = "/storage/emulated/0/CombinedImage.png";//path save result image
new PhotoComposition().execute(images, pathSaveCombinedImage);
And the result of using the above code will be as follows
You may wish to look into the Canvas object, which would make it easy to do other drawing operations as well. You can just draw your bitmaps onto a canvas where you want them, then save the resulting bitmap.
If they have transparent sections, then if you draw one on top of the other, only the non-transparent portions will overlap. It will be up to you to arrange the bitmaps however you like.
For the separate issue of re-saving your image to a png, use bitmap.compress().
Try this .
public Bitmap mergeBitmap(Bitmap frame, Bitmap img){
Bitmap bmOverlay = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), frame.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(img, 0, 0, null);
canvas.drawBitmap(frame, new Matrix(), null);
return bmOverlay;
}
Returns a bitmap image
Pass two bitmap images to your function as shown below
Bitmap img= mergeBitmap(imgone, imagetwo);
See the entire post or also see merge multiple images in android programmatically