Save image to custom folder android on onPictureTaken - android

i need to save an image to a custom folder in my phone.
my code is
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
FileOutputStream outStream = null;
try {
Random generator = new Random();
int n = 0000;
n = generator.nextInt(n);
String fName = "Image" + n + ".jpg";
outStream = new FileOutputStream(String.format(fName));
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
}
not working

#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
if(bitmap!=null){
File file=new File(Environment.getExternalStorageDirectory()+"/dirr");
if(!file.isDirectory()){
file.mkdir();
}
file=new File(Environment.getExternalStorageDirectory()+"/dirr",System.currentTimeMillis()+".jpg");
try
{
FileOutputStream fileOutputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
catch(IOException e){
e.printStackTrace();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
}
Dont forget to add permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

You can find ans from below code
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
Bitmap m_bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
String destinationPath = Environment.getExternalStorageDirectory() + "/" + "Image.jpg";
if (m_bitmap != null || destinationPath != null)
{
FileOutputStream m_out = new FileOutputStream(destinationPath);
m_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, m_out);
}
}
Hope this code helps you

You first have to create the destination folder you want to save the file into. So, in your Android sdk folder, you create the MediaFiles folder. In this folder you can then create your file.
Here's some code you can try.
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
FileOutputStream outStream = null;
try {
Random generator = new Random();
int n = 0000;
n = generator.nextInt(n);
String fName = "Image" + n + ".jpg";
outStream = new FileOutputStream(GetPathForFileName(fName));
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
}
private String GetPathForFileName(String fileName)
{
try
{
String savePath = GetSaveFolderFromConfiguration();
File file = new File(savePath + "/" + fileName);
return savePath + "/" + fileName;
}
catch (Exception ex)
{
ExceptionForm.ShowException(ex);
}
return null;
}
public static String GetSaveFolderFromConfiguration() throws Exception
{
String path = Environment.getExternalStorageDirectory().toString() + "/MediaFiles";
File f = new File(path);
if (f.exists())
return path;
else
f.mkdir();
return path;
}

Related

How to properly extract files (out of memory)?

At start up of my app I want to extract my images (if they does not exists) from drawable folder to internal app folder to use later with FileProvider. Images have dimensions 2000*2000 and average size 380kb, format png.
Those images are not to be displayed (smaller ones are used to display). They are only for file sharing and I have to keep their original size.
I get out of memory at calling
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResID);
Code
private void extractImages() {
TypedArray imgs = getResources().obtainTypedArray(R.array.smile_list_share);
File imagePath = new File(getFilesDir(), "images");
File checkImage;
for (int i = 0; i < imgs.length(); i++) {
int imageResID = imgs.getResourceId(i, 0);
if (imageResID > 0) {
String name = getResources().getResourceEntryName(imageResID);
checkImage = new File(imagePath, name + ".png");
if (!checkImage.exists()) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResID);
boolean b = saveBitmapToFile(imagePath, name + ".png", bm, Bitmap.CompressFormat.PNG, 100);
Log.e("mcheck","saved "+b+", file "+name);
Log.e("mcheck", "file does not exists " + name);
} else {
Log.e("mcheck", "file exists " + name);
}
} else {
Log.e("mcheck", "ERROR " + i);
}
}
imgs.recycle();
}
public boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format, quality, fos);
bm.recycle();
fos.close();
return true;
} catch (IOException e) {
Log.e("app", e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
You have to call recycle on your bitmap object everytime you are done with it.
Here is a good guide on how to manipulate bitmaps efficiently
https://developer.android.com/training/displaying-bitmaps/load-bitmap.html
I found that I dont need to create bitmap object at all. It is possible to obtaine intput stream from getResourses directly.
public boolean saveBitmapToFile(File dir, String fileName, int imageResourse) {
File imageFile = new File(dir, fileName);
FileOutputStream fos = null;
InputStream inputStream = null;
try {
fos = new FileOutputStream(imageFile);
inputStream = getResources().openRawResource(imageResourse);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
inputStream.close();
fos.close();
return true;
} catch (IOException e) {
Log.e("app", e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}

File saving outputstream on android

I am making an android apps that can take photos. I have written some codes to save the photos taken by the app. The directory that I want to save the file is in the internal storage and in the folder named DCIM. However, the app crashes everytime I tried to save the photo. Below is my code:
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"sdcard/DCIM/jgjk.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Is there anything wrong with the code?
This will work fine
Getting Bitmap in onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode==PIC_CROP)
{
if(resultCode==RESULT_OK)
{
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bmp = extras.getParcelable("data");
savePhoto(bmp);
}
}
}
}
public void savePhoto(Bitmap bmp)
{
dir = Environment.getExternalStorageDirectory().toString() + "/DCIM/";
File newdir = new File(dir);
newdir.mkdirs();
FileOutputStream out = null;
//file name
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
File imageFileName = new File(newdir, "crop_"+date.toString() + ".jpg");
try
{
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
out = null;
} catch (Exception e)
{
e.printStackTrace();
}
}
public String fromInt(int val)
{
return String.valueOf(val);
}

Android Save the image in sdcard

I am saving an image into sdcard, but I want that the directory folder will be automatically shown in the gallery and the image on the folder. Whenever I save the image I am rebooting my phone for the directory folder to be shown in the gallery. Is it my code that has a problem? or the phone? Please help me. Thank you so much. I dont know what to do
here's my code:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
mTempDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + "PixiePhotos" + "/";
prepareDirectory();
save.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ShowToast")
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v(TAG, "Save Tab Clicked");
viewBitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(viewBitmap);
tapimageview.draw(canvas);
canvas.drawBitmap(bp, 0, 0, paint);
canvas.drawBitmap(drawingBitmap, matrix, paint);
canvas.drawBitmap(bmpstickers, matrix, paint);
//tapimageview.setImageBitmap(mBitmapDrawable.getBitmap());
try {
mBitmapDrawable = new BitmapDrawable(viewBitmap);
mCurrent = "PXD_" + new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date()) + ".jpg";
bp1 = mBitmapDrawable.getBitmap();
tapimageview.setImageBitmap(bp1);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.JPEG, 100, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
Toast.makeText(getApplicationContext(), "Your photo has been saved", Toast.LENGTH_LONG).show();
}
});
}
private boolean prepareDirectory() {
try {
if (makeDirectory()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(this, getString(R.string.sdcard_error), 1000).show();
return false;
}
}
private boolean makeDirectory() {
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
if (mTempFile.isDirectory()) {
File[] mFiles = mTempFile.listFiles();
for (File mEveryFile : mFiles) {
if (!mEveryFile.delete()) {
//System.out.println(getString(R.string.failed_to_delete) + mEveryFile);
}
}
}
return (mTempFile.isDirectory());
}
Try this:
private boolean storeImage(Bitmap imageData, String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/myAppDir/myImages/"
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
Don't forget to add Storage Permissions
Since this is operation that saves data on external memory, it requires AndroidManifest.xml permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try it out
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.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 add permission in your maniefest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is not with the code ...
what happens over here is
After downloading the file on the sdcard the gallery is not notified with new file added or downloaded to the system
What you need to do is you have to manually Notify the gallery that ...okhay gallery file is added please show ..:)
For that you have to use MediaScannerConnection
Download the file ,scan the particular file and it will be shown in the gallery
and you are done:)

How to save a bitmap on internal storage

this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.
public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn1=(Button)findViewById(R.id.button2);
sv=(SurfaceView)findViewById(R.id.surfaceView1);
btn.setOnClickListener(this);
btn1.setOnClickListener(this);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
public void onClick(View v) {
canvas=sv.getHolder().lockCanvas();
if(canvas==null) return;
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// 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()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".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();
} catch (Exception e) {
e.printStackTrace();
}
}
Modify onClick() as follows:
#Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.
I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
To save file into directory
public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "snap_"+mTimeStamp+".jpg";
ContextWrapper wrapper = new ContextWrapper(mContext);
File file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "snap_"+ mImageName+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
Uri mImageUri = Uri.parse(file.getAbsolutePath());
return mImageUri;
}
required permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You might be able to use the following for decoding, compressing and saving an image:
#Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});

Android, can't read images I saved to data folder

My app uses the following piece of code to write out images I have resized into the app's data folder:
private void writeImage(Bitmap bmp, String filename)
{
try
{
FileOutputStream stream = openFileOutput(filename, MODE_WORLD_WRITEABLE);
bmp.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I am able to read them in a file browser (ddms) and can confirm they appear to have been written.
However, any attempt to load the images results in non-null bitmaps with width and height of -1. I am using the following code to load them:
imageList = getFilesDir().list();
Bitmap bmp = null;
for(String img : imageList)
{
try {
bmp = BitmapFactory.decodeStream(openFileInput(img));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: On further inspection, it seems, after conversion the images are of density 160 (and not 240 as they should be) also, after testing a working application it seems the -1 mWidth and -1 mHeight on the bitmaps is irrelevent.
I had same problem.my data folder given smallest image.and cursor return null pointer exception on my getDestination method.then i fixed like it
public void captureNewPhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
targetFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
targetUri = Uri.fromFile(targetFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 12);
}
And i use like in onActivityResult();
BitmapFactory.Options options = new BitmapFactory.Options();
networkBitmap = BitmapFactory.decodeFile(targetUri.getPath(),
options);
//ImageDialog(networkBitmap);
//String path = getRealPathFromUri(this, Uri.parse(targetUri.getPath()));
String myDeviceModel = android.os.Build.MODEL;
deviceName = Build.MANUFACTURER;
if (myDeviceModel.equals("GT-I9500")) {
} else if (deviceName.contains("samsung")) {
} else {
exif = ReadExif(targetUri.getPath());
if (exif.equals("6")) {
matrixx.postRotate(90);
} else if (exif.equals("7")) {
matrixx.postRotate(-90);
} else if (exif.equals("8")) {
matrixx.postRotate(-90);
} else if (exif.equals("5")) {
matrixx.postRotate(-90);
}
//matrixx.postRotate(-90);
}
networkBitmap = Bitmap.createBitmap(networkBitmap, 0, 0, networkBitmap.getWidth(), networkBitmap.getHeight(), matrixx, true);
Log.e("Taget File ", "Size " + targetFile.length());
if (networkBitmap != null) {
ImageSetting(networkBitmap, System.currentTimeMillis() + filename);
}
public void ImageSetting(Bitmap imageBitmap, final String fileName) {
networkBitmap = imageBitmap;
organizator(networkBitmap, fileName);
networkBitmap = null;
}` public void tamamlandiOndenFoto(Bitmap turnedBitmap, String filename) {
frontFotoFile = storeBitmap(networkBitmap, filename);
ondenFotoPath = ondenFoto.getAbsolutePath();
ondenFotoImageView.setImageBitmap(turnedBitmap);
}`
public File storeBitmap(Bitmap bp, String fileName) {
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File dest = new File(sd, fileName);
if (bp != null) {
try {
FileOutputStream out = new FileOutputStream(dest);
bp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Alinan hata ", " Catch hata ", e);
}
return dest;
} else {
return null;
}
}
I hope give you any idea for your problem.

Categories

Resources