I have image in my ListView. They are loaded as follows:
String iMages[] = {
"http://www.thebiblescholar.com/android_awesome.jpg",
"http://blogs-images.forbes.com/rogerkay/files/2011/07/Android1.jpg",
"http://cdn.slashgear.com/wp-content/uploads/2012/10/android-market-leader-smartphone.jpg",
"http://www.planmyworkshop.com/images/android.jpeg",
"http://www.androidguys.com/wp-content/uploads/2012/07/01-android2.jpg"
};
ArrayList<Bitmap> bitmap_array = new ArrayList<Bitmap>();
for (int i = 0; i < iMages.length; i++) {
Log.d("i-->" + i, "Url-->" + iMages[i]);
Bitmap bit = getBitmapFromURL(iMages[i]);
bitmap_array.add(bit);
}
How load them from res/drawable ? I tried different ways, but all the way past ...
Try something like this to decode a bitmap from your drawable folder:
Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_launcher);
I assume the images in your ListView are of type ImageView or subclasses (ImageButton, ZoomButton etc.).
If that is the case, just set the res image as background:
myImageView.setBackgroundResource(R.drawable.my_image);
Remember to do it only from UI thread.
You can also do like this
String imageFileName = "launcher"; // this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+imageFileName , null, null);
image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));
Related
I'm trying to create an animation out of multiple png images. Here's my code:
AnimationDrawable animation = new AnimationDrawable();
for (int i = 0; i < translate_text.length(); i++)
{
byte[] byteArray = Base64.getDecoder().decode(client._fromServer.elementAt(i));
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.sign);
image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));
animation.addFrame(image.getDrawable(), 1000);
}
animation.setOneShot(true);
animation.start();
but this only displays the last frame... Any ideas?
Edit: Probably should've done this earlier, but here goes:
translate_text is a string. It represents the image sequence. For example if the string is "bob" then there should be 3 images: the letter B, the letter O and the letter B.
client._fromServer is a vector of strings. Each string is the image itself encoded in base64. That's why client._fromServer.elementsAt(i) is a string that needs to be decoded and turned into byteArray.
I think it is because you get the Drawable from the same ImageView.
When you do image.setImageBitmap() it updates the reference of the Drawable in the ImageView and the AnimationDrawable gets affected also.
You should use a different Drawable instance for each addFrame call.
Something like that:
AnimationDrawable animation = new AnimationDrawable();
ImageView image = (ImageView) findViewById(R.id.sign);
for (int i = 0; i < translate_text.length(); i++)
{
byte[] byteArray = Base64.getDecoder().decode(client._fromServer.elementAt(i));
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false);
Drawable drawable = new BitmapDrawable(getResources(), scaledBitmap);
animation.addFrame(drawable, 1000);
}
animation.setOneShot(true);
animation.start();
please read the full question before marking it as duplicate or down-vote it.
i am developing an app what can slice through a picture and run google vision to recognize text in each chunk or slice of picture and run OCR to detect that the circle bubble is filled or not in the chunk. but when i am slicing the Bitmap image in an array and pass it to other activity for the process it crashes for over use of memory. I know i can compress it but i tried that already (though i did not wanted to compress it since i need to run google vision and may not able to extract text accurately) but it did not work since there are 46 slices of image. How can i do so without uploading on cloud fetch it again for process since it might take long. any alternative solution is very welcome as well. i am stuck on this for quite a while.
import android.content.Intent;.....
public class ProcessesdResult extends AppCompatActivity {
TextView tvProcessedText;
Button btnImageSlice;
Bitmap image;
int chunkNumbers =46;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_processesd_result);
Intent intenttakeattendance = getIntent();
String fname = intenttakeattendance.getStringExtra("fname");
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
String photoPath = myDir+"/sams_images/"+ fname;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
image = BitmapFactory.decodeFile(photoPath, options);
btnImageSlice=findViewById(R.id.btnimageslice);
btnImageSlice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
splitImage(image, chunkNumbers) ;
}
});
}
private void splitImage(Bitmap image, int chunkNumbers) {
//For the number of rows and columns of the grid to be displayed
int rows =23;
int cols =2;
//For height and width of the small image chunks
int chunkHeight,chunkWidth;
//To store all the small image chunks in bitmap format in this list
ArrayList<Bitmap> chunkedImages = new ArrayList<Bitmap>(chunkNumbers);
//Getting the scaled bitmap of the source image
Bitmap scaledBitmap = Bitmap.createScaledBitmap(image, image.getWidth(), image.getHeight(), true);
chunkHeight = image.getHeight()/rows;
chunkWidth = image.getWidth()/cols;
//xCoord and yCoord are the pixel positions of the image chunks
int yCoord = 0;
for(int x=0; x<rows; x++){
int xCoord = 0;
for(int y=0; y<cols; y++){
chunkedImages.add(Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth, chunkHeight));
xCoord += chunkWidth;
}
yCoord += chunkHeight;
}
//Start a new activity to show these chunks into a grid
Intent intent = new Intent(ProcessesdResult.this, ChunkedImageActivity.class);
intent.putParcelableArrayListExtra("image chunks", chunkedImages);
startActivity(intent);
}
}
This is the image type i want to slice in pieces
You dont want to pass objects between activities, especially not huge objects like bitmaps. I would suggest saving your bitmaps in the devices file system and then passing a list of URI's. Saving the bitmaps like this and recycling your bitmaps after you are done using them should also reduce the RAM usage during your loop where you slice up the image.
For saving bitmaps as files i would refer to this question: Saving and Reading Bitmaps/Images from Internal memory in Android
So basically your loop should look like this:
for(int x=0; x<rows; x++){
int xCoord = 0;
for(int y=0; y<cols; y++){
Bitmap image = Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth, chunkHeight);
Uri uri = saveBitmapAsFile(image);
image.recycle();
xCoord += chunkWidth;
}
yCoord += chunkHeight;
}
use android:largeHeap="true" in manifest if you still get the same error then try this :
instead of sending "intent.putParcelableArrayListExtra("image chunks", chunkedImages);"
bitmap to another activity, save that image to local storage and use path wherever you want.
I recommended for create another data(Bitmap) store class with static.
Use this class for save bitmaps and call another activity for read.
This link helpful.
I want to retrieve a list of images from SQLite.
This is my 'getImage()' method
public List<byte[]> getImage(int i) {
List<byte[]> list = new ArrayList<>();
String selectImage = "SELECT VocabImage FROM Vocab WHERE VocabTopic =" + i;
Cursor c = database.rawQuery(selectImage, null);
if(c.moveToFirst())
do{
list.add(c.getBlob(c.getColumnIndex("VocabImage")));
}while(c.moveToNext());
c.close();
return list;
}
This is my java class where I want to call my getImage() method. But there is an error saying that it cannot resolve symbol 'length' in (data.length) in the BitmapFactory line. Anyone has any idea how to solve this? Thank you.
Intent intent = getIntent();
int topicId = intent.getIntExtra("SelectedTopicId", 1);
databaseAccess.open();
List<byte[]>data = databaseAccess.getImage(topicId);
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(image);
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
change to
Bitmap image = BitmapFactory.decodeByteArray(data.get(position), 0, data.get(position).length); // pass position for which you want length.
you need to change like this: list.get(0).length for get image at index 0.
I'm trying to create a Bitmap or Drawable from existing file path.
String path = intent.getStringExtra("FilePath");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPreferredConfig = Bitmap.Config.ARGB_8888;
mImg.setImageBitmap(BitmapFactory.decodeFile(path));
// mImg.setImageBitmap(BitmapFactory.decodeFile(path, option));
// mImg.setImageDrawable(Drawable.createFromPath(path));
mImg.setVisibility(View.VISIBLE);
mText.setText(path);
But setImageBitmap(), setImageDrawable() doesn't show an image from the path. I've printed path with mText and it looks like : /storage/sdcard0/DCIM/100LGDSC/CAM00001.jpg
What am i doing wrong? Anyone can help me?
Create bitmap from file path:
File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.
I think you are giving the wrong file path.
It works for me:
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Edit:
If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:
String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(sdcardPath);
here is a solution:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)
If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.
For Drawable -
Drawable drawable = Drawable.createFromPath(your path in string);
For Bitmap -
Bitmap bitmap = BitmapFactory.decodeFile(your path in string);
How simple it was hope you like
static ArrayList< Drawable> d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
myDrawable = Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
d.add(myDrawable);
}
you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.
declare a HashMap somewhere in your class:
private static HashMap<String, Integer> images = null;
//Then initialize it in your constructor:
public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}
Now for access -
String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);
I am trying to display an image in my app that changes everytime I press a button.
The name of the image that should be shown is in my object. I can get the name of the image with
String nameOfImage = myObhect.get(i).getImageName();
Now, I want to display the current image with
iv.setImageResource(R.drawable.notruf);
Using setImageResource , I don´t know how to bring the name of my image in setImageResource because, for example
iv.setImageResource(R.drawable. + aktbild) isn´t possible for sure.
I also tried the way with setImageDrawable but that does not work for me.
I use similar solution in my application :
Context mContext = this; // I supposed you're in Activity
String imgName = fragenkatalog.get(i).getBild();
int resId = mContext.getResources().getIdentifier(imgName,
"drawable", mContext.getApplicationInfo().packageName);
if(resId > 0){
iv.setImageResource(resId);
}
I believe that this code will help u..
String aktbild = fragenkatalog.get(i).getBild();
byte[] decodedString = Base64.decode(aktbild , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
After that, if you want to resize that image use this code.
int width=75;
int height=75;
Bitmap resizedbitmap=Bitmap.createScaledBitmap(decodedByte, width, height, true);
finally set image into ImageView.
Icon.setImageBitmap(resizedbitmap);`