I'm currently storing the photos like so in the SharedPreferences after it's captured using ACTION_IMAGE_CAPTURE intent:
if (requestCode == REQUEST_IMAGE_CAPTURE_TWO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageTwo.setImageBitmap(imageBitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("image_two", encodedImage);
edit.commit();
}
Instead I'd like to store this image to the SD card and the url to the file path in shared preferences, so that I can load the images using the filepath and I'm able to attach these photos with the ACTION_SEND intent. It appears I can't do that with the way I'm currently storing the images.
This will return file name of saved image in sdcard so now you can save it in shared preferences or you can modify as you need.
public static String saveImage(Bitmap imageBitmap) {
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory + "/Folder_Name");
dir.mkdir();
String fileName = "image" + System.currentTimeMillis() + ".jpeg";
File image = new File(dir, fileName);
fileName = image.getPath();
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
fileName = Constants.ERROR_IMAGE_SAVING;
e.printStackTrace();
} catch (IOException e) {
fileName = Constants.ERROR_IMAGE_SAVING;
e.printStackTrace();
}
return fileName;
}
There is solution:
public static String saveEncodedImage(String folderName, String imgFileName, String encodedImage) {
//check sdcard is available
String sdStatus = Environment.getExternalStorageState();
if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
// sdcard not avaliable
return "";
}
String urlToPath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator
+ folderName;
File folder = new File(urlToPath);
if (!folder.exists()){
folder.mkdir();
}
urlToPath = urlToPath + File.separator + imgFileName;
File imgFile = new File(urlToPath);
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(imgFile));
bufferedWriter.write(encodedImage);
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return urlToPath;
}
You can use it like this:
if (requestCode == REQUEST_IMAGE_CAPTURE_TWO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageTwo.setImageBitmap(imageBitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//save to sdcard
String urlToImage = saveEncodedImage("images","image_two",encodedImage);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("image_two", urlToImage);
edit.commit();
}
Related
"I have fetch an image from ImageView and save it in root directory but when i go to pic the same image using from gallery , the created folder is not visible in gallery picker . but when i check the folder from file manager it show me the created folder with image",
#I have used this code for saving the image in my directory.#
public void saveImageToSdCard(Bitmap bitmap1) {
File sdCard = Environment.getExternalStorageDirectory();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (sdCard != null) {
File directory = new File(sdCard.getAbsolutePath() + "/My_folder");
if (directory.exists()) {
directory.delete();
Log.e("it run","directoty is exists");
}
directory.mkdirs();
String strImageName = File.separator + "IMG_" + timeStamp + ".jpg";
File file = new File(directory, strImageName);
// strFinalImage = file.getAbsolutePath();
// Log.e(TAG + "strFinalImage22", strFinalImage + "");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
fileOutputStream.write(bytes.toByteArray());
fileOutputStream.flush();
fileOutputStream.close();
// Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getActivity(),"Sd card mount", Toast.LENGTH_SHORT).show();
}
}
-------------------------------------------------------------------
# Intent code for gallery #
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 0);
-------------------------------------------------------------------
# OnActivityResultCode() #
Uri pickedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
Log.e("Gallery", "File URI:" + imagePath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
cursor.close();
I have write code to convert image from file location into base64. I can easily convert image into base64 from absolute file location like: C:/Users/Java Engineer/Desktop/test/gallery/magar/Kanuglam.jpg , but I can not convert from location like
. I want to convert image to use in android from web-service.
Here is code sample :
/**
* TEST JSON
*/
String convertToJsonArrayWithImageForMovieDetailTest(ResultSet rs) {
System.out.println("I am insied json converter");
JSONArray list = new JSONArray();
JSONObject obj ;
//File file;
File locatedFile;
FileInputStream fileInputStream;
try {
while (rs.next()) {
obj = new JSONObject();
System.out.println("inside RS");
System.out.println("date is there ha ha ");
obj.put("movie_name", rs.getString("name"));
obj.put("movie_gener", rs.getString("type"));
String is_free_stuff = rs.getString("is_free_stuff");
if (is_free_stuff == "no") {
is_free_stuff = "PAID";
} else {
is_free_stuff = "FREE";
}
obj.put("movie_type", is_free_stuff);
//String movie_image = rs.getString("preview_image");
//this does not work
String movie_image = "http://www.hamropan.com/stores/slider/2016-09-10-852311027.jpg";
//this works for me
// file = new File("C:/Users/Java Engineer/Desktop/Nike Zoom Basketball.jpg");
locatedFile = new File(movie_image);
// Reading a Image file from file system
fileInputStream = new FileInputStream(locatedFile);
if (locatedFile == null) {
obj.put("movie_image", "NULL");
} else {
byte[] iarray = new byte[(int) locatedFile.length()];
fileInputStream.read(iarray);
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(iarray);
String imageString = new String(img64);
obj.put("movie_image", imageString);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list.toString();
}
this block of code works for me but it seem slow
public String imageConvertMethod(String url) throws Exception{
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream input = new URL(url).openStream()) {
byte[] buffer = new byte[512];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
byte [] byte_array = output.toByteArray();
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(byte_array);
String imageString = new String(img64);
return imageString;
}
Ok, try this
bitmap = getBitmapFromUrl(image_url);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] array = stream.getByteArray();
encoded_string = Base64.encodeToString(array, 0);
Method wo load image from url
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#thanks to Fabio Venturi Pastor
Try this:
ImageUri to Bitmap:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
}
}
Encode Bitmap in base64
private String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
Encode from FilePath to base64
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
output:
reference :
Take picture and convert to Base64
I keep a photo with my application to the array Bitmap.Then when I did need, I call the shots feature saveAll() as shown in the code below
public void saveAll(View view) {
for (Bitmap b : arrBitmap) {
SystemClock.sleep(1000);
try {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(convertBitmapToByteArray(b));
fos.close();
Toast.makeText(context, "Picture saved: " + pictureFile.getName(),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
}
private byte[] convertBitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream(bitmap.getWidth() *
bitmap.getHeight());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File("/sdcard/", "JCG Camera");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" +
timeStamp + ".jpg");
return mediaFile;
}
and photo is saved very strange at first may not Save or Save all but the first or the first did not survive, but then when I further tested the code they may appear,but every time Toast shows that all is saved.Please tell me
what am I doing wrong?
I store image auto take camera image.Bimap value ever null after get image from file path.How we can do it? pleases help us.
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG"
+ timeStamp + ".jpg");
/* mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".JPEG");*/
return mediaFile;
}
auto take camera method
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
calling camera onCreate
private Camera mCamera;
mCamera.takePicture(null, null, mPicture);
I already get image picture value /storage/emulated/0/Pictures/MyCameraApp/IMG20151215_141506.jpg
when I set to bitmap the bitmap value return null how we can set image file path string to bitmap
picture = getOutputMediaFile().getAbsolutePath();
File file=new File(picture);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] image = stream.toByteArray();
String img_str = Base64.encodeToString(image, Base64.DEFAULT);
I'm also try the same like this
picture = getOutputMediaFile().getPath();(OR)
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath);(OR)
Bitmap bitmap = BitmapFactory.decodeFile(picture);(OR)
I'm working on this Camera application but I'm having trouble displaying the image that the user takes. The camera, preview, and capture buttons work perfectly on the main activity. Right now, the application saves the photo to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp" But I DON'T want the images to save there. I just want to pass that image to the next activity, (Not save it to a public directory). Is there a way to do this? I've looked at the tutorials but can't figure out how to implement MODE.PRIVATE.
Here's where it is called:
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
return pictureFile.getPath();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
return null;
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
Intent intent = new Intent(mContext, ImageDisplayActivity.class);
intent.putExtra(ImageDisplayActivity.KEY_PATH, result);
startActivity(intent);
}
}
}.execute();
}
Here is the code for the method:
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
Try this one ,
ActivityOne.Java
try {
//Write file
String filename = "photo.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 200, stream);
//Cleanup
stream.close();
//Pop intent
Intent mIntent= new Intent(this, ActivityTwo.class);
in1.putExtra("bitmap", filename);
startActivity(mIntent);
} catch (Exception e) {
e.printStackTrace();
}
ActivityTwo.Java
Bitmap bmp = null;
String filename = getIntent().getStringExtra("bitmap");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
and set Imageview with bitmap you can get your bitmap which you captured from camera
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Look at the example :
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
So basically, you just need to have a FILENAME to create a file on private mode.
Just keep the last part your method getOutputMediaFile(int type) it should be something like this :
private static File getOutputMediaFile(int type){
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = "IMG_"+ timeStamp + ".jpg";
} else {
return null;
}
return mediaFile;
}
and then just change this try of your doInBackground function :
try {
FileOutputStream fos = openFileOutput(pictureFile, Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return pictureFile;
}
And just give the path to your other Activity and create a bmp
String filepath = intent.getStringExtra("EXTRA_FILE");
java.io.FileInputStream in = openFileInput(filepath);
Bitmap bmp = BitmapFactory.decodeStream(in)