Where to save an Image - android - android

I am developing Android application where users choose an icon image from a gallery. I need to save that image (bitmap), so I can use it when application is restarted.
Any simple example would be greatly appreciated.
Thanks.

Make use of the code below to save an image:
void saveImage() {
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Save");
alertDialog.setMessage("Your drawing had been saved:)");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
And to retrive image from sdcard:
Supose you retrieves the image from sdcard in your Import.java Acitivty like that:
File file = new File(getExternalFilesDir(null), "MyFile.jpg");
So, once you have your image in a File object, you just need to put its path on a Intent that will be used to be a result data, which will be sent back to the "caller" activity. In some point of your "called" acitivity you should do that:
Intent resultData = new Intent();
resultData.putExtra("imagePath", file.getAbsolutePath());
setResult(RESULT_OK,returnIntent);
finish();
Your method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_OK)
{
String path = data.getStringExtra("imagePath");
}
}
That's it!
Hope it helps :)

http://developer.android.com/guide/topics/data/data-storage.html
I would suggest using external storage

Use SharedPreferences to store image in Base64 String representation.
Bitmap imageBitmap = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream );
byte[] byte = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(byte , Base64.DEFAULT);
SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences .edit();
sharedPreferencesEditor.putString("image_data", encodedImage).commit();
While retrieving, convert Base64 representation back to Bitmap.
SharedPreferences sharedPreferences = getSharedPreferences("SharedPreferencesName", <Mode>);
String encodedImage = sharedPreferences.getString("image_data", "");
if( !encodedImage.equals("") ){
byte[] byte = Base64.decode(encodedImage , Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(byte, 0, byte.length);
imageView.setImageBitmap(bitmap);
}

Related

Upload pdf or txt in app android and convert to base64

I'm working for an application in witch i need to upload a file ( image from camera or gallery, pdf or txt from documents), convert in base64 and add the String with the base64 in an array. I resolved for image both from camera and from gallery- Now i need to do the same with the documents. How ca I upload a document from my device to my app and convert it in base64? This is my code for images:
private void selectImage(){
final CharSequence[] item={"Camera","Document","Cancel"};
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Carica");
builder.setItems(item, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(item[i].equals("Camera")){
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,Request_camera);
}
else if(item[i].equals("Document")){
Intent intent3 = new Intent();
intent3.setType("*/*");
intent3.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent3,"Choose File to Upload.."),PICK_FILE_REQUEST);
Uri.parse(Environment.getExternalStorageDirectory().toString());
}
else if(item[i].equals("Cancel")){
dialog.dismiss();
}
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==Request_camera && button1==1){
Bundle bundle=data.getExtras();
final Bitmap bpm= (Bitmap)bundle.get("data");
uploadImage.setImageBitmap(bpm);
bitmapToBase64(bpm);
String mynewString=bitmapToBase64(bpm);
mydocument.set(0,mynewString);
decode64.setText(mynewString);
getFileExt(uploadImage.toString());
}
else if(requestCode==Request_camera && button1==2){
Bundle bundle=data.getExtras();
final Bitmap bpm= (Bitmap)bundle.get("data");
imageView2.setImageBitmap(bpm);
bitmapToBase64(bpm);
String mynewString=bitmapToBase64(bpm);
decodee2.setText(mynewString);
decodee2.setTextColor(Color.GREEN);
}
else if(requestCode==Request_file){
Uri selectImageUri=data.getData();
uploadImage.setImageURI(selectImageUri);
String newNome=getFileName(selectImageUri);
decode64.setText(newNome);
String realPath=selectImageUri.toString();
decodee2.setText(realPath);
File file=new File(newNome);
getStringFile(file);
String myDecode=getStringFile(file);
mydocument.set(0,myDecode);
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
Thanks!!
To convert your image to Base64;
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByte = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imageByte, Base64.DEFAULT);
}
You need first to convert it to bitmap.

How to save file in Android to specific folder?

btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ivdisplayphoto.setDrawingCacheEnabled(true);
Bitmap bitmap = ivdisplayphoto.getDrawingCache();
String message = getIntent().getExtras().getString("");//== String message= "/folder1/folder2/"
String root = (Environment.getExternalStorageDirectory().getPath()+message);
// String root = (Environment.getExternalStorageDirectory().getPath()+""/folder1/folder2/");
text.setText(root);
final File newDir = new File(root + "//saved_imag");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "safed to your folder", Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
}
});
Hey I'm new to Android and I have been trying to make an app.
I am having trouble with part of saving the camera images into the newly created folder.
the problem is in to message variable i can create the file "newDir" if i use simple string "/folder1/folder2/",but if I use the "message" variable
  I cant create it
// Your problem with message variable. Below is working code please go through it.
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
}
});
//save you image when calling the onActivityResult method after capture image.
//When user click image vai camera then directly store to save_image folder.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image_" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// But the problem it is I want to record the photo in the path rot=root+message
// In another activity I have a qr-code scanner, every qr-code scanned corresponds to a path the content of every qr-code pass of the first activity to the second, the content is stored in the variable "message".
//Then i am obliged to use the variable "message" so that I draw to change the path to store my photo.
String message = getIntent().getExtras().getString("");
String root=Environment.getExternalStorageDirectory().toString();
String rot = root+message;
// String root = (Environment.getExternalStorageDirectory().getPath()+""/folder1/folder2/");
final File newDir = new File(rot + "/dossier_photos");
Here you did simple mistake with Path :
Environment.getExternalStorageDirectory().getPath() = /storage/emulated/0
Environment.getExternalStorageDirectory().getPath()+message = /storage/emulated/0message
So you got error,
here path should be like below:
String root = (Environment.getExternalStorageDirectory().getPath()+"/"+message);

How can I open images that save in internal storage (cache folder in Android/data/%package%/cache) in android gallery

After image was download, I save it in an internal storage at
Android/data/%packagename%/cache directory. below is a code.
private class SaveImageToStorage extends AsyncTask<Void,Void,Void>
{
String picName;
Bitmap bitmap;
public SaveImageToStorage(String name, Bitmap bitmap)
{
this.picName = name;
this.bitmap = bitmap;
}
#Override
protected Void doInBackground(Void... params) {
if(bitmap != null && !picName.isEmpty()) {
File file = new File(feedImagesCacheDir.getPath(), extractImageNameFromUrl(picName));
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.WEBP, 80, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
And after all of this I just want to open the image in android gallery.
I try below code and it doesn't work.It show me Toast "can't find the image".
So I've tried remove "file://", then it open gallery with nothing but something like broken image icon.
private void openImageInGallery(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://"+getFeedImagesCacheDir().getPath() + "/" + imgName+".webp"), "image/*");
startActivity(intent);
}
I think that maybe I save it in cache folder, so its became private with only access to my app.
How can I fix this?
Thanks.Sorry for my bad ENG.
Cache Image are not view directly because is save like encrypted format so first you download that image and save into SD card. use below code.
String root = Environment.getExternalStorageDirectory().toString();
String wallpaperFilePath=Android/data/%packagename%/cache/imagename;
File cacheDir = GlobalClass.instance().getCacheFolder(this);
File cacheFile = new File(cacheDir, wallpaperFilePath);
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
wallpaperBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
By using this line you can able to see saved images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
You can download images into DCIM (your gallery folder in sdCard).
Then use below to open gallery:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
If you want to get result URI or do anything else use this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
Hope this help!

Save bitmap from selected file as new file into my own app folder

I just want to know on how can I save the image I selected from the gallery into my own folder as well as rename it but all the properties should remain in tact. Well I already have this method which came from a tutorial from vogella where you can select from gallery and display it as a preview. But instead of preview I just wanted do the thing I mentioned above. Here's the code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/*this method is used for getting and selecting image from gallery and display it in the imageView*/
InputStream stream = null;
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
if (bitmap != null) {
bitmap.recycle();
}
stream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(stream);
preview.setImageBitmap(bitmap);
//instead setting it in preview, save it in your image folder and rename it
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Well I do know some parts about saving a file but I'm really lost with this one so hope someone can help me. Thanks in advance.
private String saveToInternalSorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("directoryName", Context.MODE_PRIVATE);
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
// fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
Do this
public String writeFileToInternalStorage(Context context, Bitmap outputImage) {
String fileName = Long.toString(System.currentTimeMillis()) + ".png";
final FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
outputImage.compress(CompressFormat.PNG, 90, fos);
}

how to send images from one activity to other (using file path)

In my app, I am loading images from url's in listview. And onclick of list item I want to show it on next activity. I can pass bitmap through intent,But considering the size restriction of data that can be send through intent I dont want to send this way.
Anybody knows the better way of passing image from one activity to other.
I have heard about storing image in file and sending filepath using intent But don't know how?Please tell me how can I do it?
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
imageview=(ImageView) view.findViewById(R.id.icon);
description=(TextView) view.findViewById(R.id.firstLine);
rating=(TextView) view.findViewById(R.id.text1);
noofDownloads=(TextView) view.findViewById(R.id.text2);
noofComments=(TextView) view.findViewById(R.id.text3);
imageId=(TextView) view.findViewById(R.id.imageIdText);
publishdate=(TextView) view.findViewById(R.id.thirdLine);
attribution=(TextView) view.findViewById(R.id.attributionText);
Intent intent = new Intent(PicturesList.this, PictureDetail.class);
String fileName=description.getText().toString();
fileclass=new FileClass();
fileclass.saveImage(bitmap,fileName);
Intent intent = new Intent(PicturesList.this, PictureDetail.class);
intent.putExtra("imagePath",fileclass.getPath());
intent.putExtra("Description",description.getText());
intent.putExtra("Rate",rating.getText());
intent.putExtra("Downloads",noofDownloads.getText());
intent.putExtra("Comments",noofComments.getText());
intent.putExtra("PublishTime",publishdate.getText());
startActivity(intent);
}
});
}
And I have save images from ListAdapter
in
getview()
{
String fileName=lolpic.getDescription().toString();
FileClass fileclass=new FileClass();
fileclass.saveImage(bitmap,fileName);
and FileClass.java
public class FileClass {
Picture pic;
File file;
public void saveImage(Bitmap myBitmap,String fileName) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pictures");
String fname = fileName+".png";
file = new File (myDir, fname);
if (file.exists ())
{
file.delete ();
}
try {
FileOutputStream out = new FileOutputStream(file);
//myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
out.write(byteArray);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getPath()
{
return file.getPath();
}
}
use this to store image in sdcard
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "MyImage.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and next get the image path from file.getpath()
and use
intent.putExtra("imagePath", file.getpath());
to send the image through intent and use
String image_path = getIntent().getStringExtra("imagePath");
Bitmap bitmap = BitmapFactory.decodeFile(image_path);
myimageview.setImageDrawable(bitmap);
in your receiving activity to display an image onto the imageview named myimageview
Based on comments, looks like it should be myimageview.setImageBitmap(bitmap) . Didn't test this. But give a try to this also if above doesn't work
sending Activity
final String root = Environment.getExternalStorageDirectory().getAbsolutePath();
pathToImage = root + "/my/image/path/image.png";
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("imagePath", pathToImage);
startActivity(intent);
And in you receiving activity:
String path = getIntent().getStringExtra("imagePath");
Drawable image = Drawable.createFromPath(path);
myImageView.setImageDrawable(image);

Categories

Resources