Android: Loading images from the internal folder by using String ID - android

I'm new to android programming and have been trying to figure out how to
load an image (at startup) from the assets folder and save that image in a object (What kind of object should i save it into?)
So that when i want to display that object in an imageview i can just point to it and retreve an imageview displaying that image.
I tryed looking for similar posts but there was nothing specific enough for me to understand fully.
Is there any way to do this or is it a completely wrong approach to using images in android?
Thanks in advance

Here is the code you need. It gets the AssetManager, reads a bitmap from assets, and places the bitmap in an image view.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the AssetManager
AssetManager manager = getAssets();
// Read a Bitmap from Assets
try {
InputStream open = manager.open("icon.png");
Bitmap bitmap = BitmapFactory.decodeStream(open);
// Assign the bitmap to an ImageView in this layout
ImageView view = (ImageView) findViewById(R.id.ImageView01);
view.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
The onCreate method runs when the activity is created. The content view is set and then the AssetManager is retrieved. The AssetManager opens the image "icon".png and saves it as a bitmap. The bitmap can now be assigned to imageviews.

Related

resourceID from image in assets subfolder only works for some files

I have an assets subfolder and images on it all png's some bigger, I'm writing a hybrid app from Angular so I pass via an interface the name of a file to pop it in an activity I pass only the name not the extession. It works for some files but not for others (a bigger one on my case) is there a reason for that???, I'm using this basic code below, the smaller file resID has a number for the bigger file it comes out as 0. The png with the problem does load on a basic page in angular, I want to pop a zoomer of that image. Probably I could place a copy in the Drawable res folder, but Angular needs it hanging from my assets.
image = (TouchImageView) findViewById(R.id.cur_img);
if( getIntent().hasExtra("imageResName") ) // set it to passed image
{ // a popup pass in the image
String curResName =getIntent().getExtras().getString("imageResName");
// gte the di from a drawble ..it wprks
int resID = getResources().getIdentifier(curResName , "drawable", getPackageName());
image.setImageResource(resID);
}
UPDATE: Yep that code will NOT work I could pull an SO answer where
I probably misunderstood it ... this is the mod'ed code that will work
if( getIntent().hasExtra("imageResName") ) // set it to passed image
{ // a popup pass in the image
String curResName =getIntent().getExtras().getString("imageResName");
Bitmap bitmap=null;
try
{ // for image in: /assets/imagenes/xxx.png
AssetManager assetManager = getApplicationContext().getAssets();
InputStream istr = assetManager.open("imagenes/" + curResName + ".png" );
bitmap = BitmapFactory.decodeStream(istr);
istr.close();
}
catch (Exception ex)
{
bitmap = null;
}
finally
{
image.setImageBitmap(bitmap);
}

Save RelativeLayout with content as an image

I have relativelayout (A template) where it contain textboxes whose content is populated at runtime.On clicking save button,I need to save the template as an image in SD card.Is it possible.
I referred the below link:
How do I convert a RelativeLayout with an Imageview and TextView to a PNG image?
But the image saved cannot be opened.
Is my requiremnet possible.Or else please advice how can I achieve it.
I am behind this for several days.I am new to ANdroid.Please help.
Thanks in Advance.
You can pass any view or layout to devBitmapFrmViewFnc function and get the bitmap. You can save the bitmap in jpeg using devImjFylFnc.
|==| Dev Bitmap Image from View :
Bitmap devBitmapFrmViewFnc(View viewVar)
{
viewVar.setDrawingCacheEnabled(true);
viewVar.buildDrawingCache();
return viewVar.getDrawingCache();
}
|==| Create a JPG File from Bitmap :
static void devImjFylFnc(String MobUrlVar, Bitmap BitmapVar)
{
try
{
FileOutputStream FylVar = new FileOutputStream(MobUrlVar);
BitmapVar.compress(Bitmap.CompressFormat.JPEG, 100, FylVar);
FylVar.close();
}
catch (Exception ErrVar) { ErrVar.printStackTrace(); }
}

Bitmapfactory example

I want to create a dynamic image view where every image in my gallery will going to use bitmapfactory and not image drawable that binds in the image view. Is there some sites that has bitmapfactory tutorial for this? i believe that using bitmapfactory uses less memory that binding the image into image view? Is this right? I want also to minimize the risk of memory leaks thats why I want to use bitmapfactory. Please help. I cant find basic examples that teaches bitmapfactory.
Building Bitmap Objects
1) From a File
Use the adb tool with push option to copy test2.png onto the sdcard
This is the easiest way to load bitmaps from the sdcard. Simply pass the path to the image to BitmapFactory.decodeFile() and let the Android SDK do the rest.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
}
}
All this code does is load the image test2.png that we previously copied to the sdcard. The BitmapFactory creates a bitmap object with this image and we use the ImageView.setImageBitmap() method to update the ImageView component.
2) From an Input stream
Use BitmapFactory.decodeStream() to convert a BufferedInputStream into a bitmap object.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/sdcard/test2.png");
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
}
This code uses the basic Java FileInputStream and BufferedInputStream to create the input stream for BitmapFactory.decodeStream(). The file access code should be surrounded by a try/catch block to catch any exceptions thrown by FileInputStream or BufferedInputStream. Also when you're finished with the stream handles they should be closed.
3) From your Android project's resources
Use BitmapFactory.decodeResource(res, id) to get a bitmap from an Android resource.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
image.setImageBitmap(bMap);
}

Creating image from current View. How To?

My application is some kind of "mini paint" and I would like to save my current view to the device memory... I would like to do the the opposite process too (Load an image from the device memory and set it as my currentview)
MiniPaint
yeah that's suppose to be a flamingo, I'm an artist!
Haven't tried it myself, but this answer shows taking a screenshot programmatically by getting the root view and saving off its drawing cache. That may be all you need to save your painting.
EDIT: Fixed link
First off I am assuming you are performing this drawing by overriding the onDraw() method on a View object, which passes in a Canvas object that you then perform some drawing operations on.
Here's a very basic way to approach this problem. There are probably lots of additional considerations to take into account, such as the file format(s) you read from and write to, and some extra error handling in the I/O code. But this should get you going.
To save what drawing you currently have, write out your View's drawingCache to a Picture object, then use the Picture's writeToStream method.
To load a pre-existing picture, you can use the Picture.readFromStream method, then in your onDraw call, draw the loaded picture to your Canvas.
To Wit:
/**
* Saves the current drawing cache of this View object to external storage.
* #param filename a file to be created in the device's Picture directory on the SD card
*/
public void SaveImage(String filename) {
// Grab a bitmap of what you've drawn to this View object so far
Bitmap b = this.getDrawingCache();
// It's easy to save a Picture object to disk, so we copy the contents
// of the Bitmap into a Picture
Picture pictureToSave = new Picture();
// To copy the Bitmap into the Picture, we have to use a Canvas
Canvas c = pictureToSave.beginRecording(b.getWidth(), b.getHeight());
c.drawBitmap(b, 0, 0, new Paint());
pictureToSave.endRecording();
// Create a File object where we are going to write the Picture to
File file = new File(this.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
try {
file.createNewFile();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
// Write the contents of the Picture object to disk
try {
OutputStream os = new FileOutputStream(file);
pictureToSave.writeToStream(os);
os.close();
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
/**
* Returns a Picture object loaded from external storage
* #param filename the name of the file in the Pictures directory on the SD card
* #return null if the file is not found, or a Picture object.
*/
public Picture LoadImage(String filename) {
// Load a File object where we are going to read the Picture from
File file = new File(this.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);
Picture pictureToLoad = null;
try {
InputStream is = new FileInputStream(file);
pictureToLoad = Picture.createFromStream(is);
is.close();
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
// Return the picture we just loaded. Draw the picture to canvas using the
// Canvas.draw(Picture) method in your View.onDraw(Canvas) method
return pictureToLoad;
}
Useful links I read to figure this out:
Reference on generating file paths in the device's external storage
Picture
Canvas
Bitmap

Read a image from internal memory in Android

I have saved a image in internal memory. For example I saved it as test.jpg. Now I want to show it in a imageview. I have tried this:
ImageView img = (ImageView)findViewById(R.id.imageView1);
try {
img.setImageDrawable(Drawable.createFromPath("test.jpg"));
} catch (Exception e) {
Log.e(e.toString());
}
And get the following message in LogCat:
SD Card is available for read and write truetrue
Any help or reference please?
public class AndroidBitmap extends Activity {
private final String imageInSD = "/sdcard/er.PNG";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
ImageView myImageView = (ImageView)findViewById(R.id.imageview);
myImageView.setImageBitmap(bitmap);
}
}
or
final Bitmap bm = BitmapFactory.decodeStream( ..some image.. );
// The openfileOutput() method creates a file on the phone/internal storage in the context of your application
final FileOutputStream fos = openFileOutput("my_new_image.jpg", Context.MODE_PRIVATE); // Use the compress method on the BitMap object to write image to the OutputStream
bm.compress(CompressFormat.JPEG, 90, fos);
hope it works...
Take a look at the doc..
You don't need to "know" where the image is stored. You just need to hold on to what you saved it as, and then you can read it back again.
The question is... did you save the file there? Or are you confusing this with images that you have compiled into the application? If it's the latter, the documentation also talks about how to read those, they are not the same as files that you have written to the device, they're part of the app package.
Welcome to Stack! If you find answers useful don't forget to upvote them and mark them as "correct" if they solve your problems.
Cheers.

Categories

Resources