jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//int imageNum = 0;
String Name = PatientInfo.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory().toString() + Name);
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
// String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
// File output = new File(imagesFolder, fileName);
/* while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}*/
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
This is a code example. I am trying to create folder with a userinput when it is entered. Each time i need to create new folders on entering new username. But in this there is something missing.Any suggestions will be helpful.
Change
File imagesFolder = new File(Environment.getExternalStorageDirectory().toString() + Name);
withFile
File imagesFolder = new File(Environment.getExternalStorageDirectory(), Name);
Please be sure to have also the WRITE_EXTERNAL_PERMISSION in the manifest, and that Name is not null
Related
I'm trying to save the image from API and is always going to catch.
public void saveSkin() {
ivSkinSaver.buildDrawingCache();
Bitmap bm = ivSkinSaver.getDrawingCache();
OutputStream Out = null;
Uri outputFileUri;
try {
File mediaFile;
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "MI_" + timeStamp + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
Out = new FileOutputStream(mediaFile);
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, Out);
Out.flush();
Out.close();
} catch (Exception e) {
}
}
I'm trying to share an image but I don't know why I'm failing, could you help me please?
String imageUrl = web.get(position).getImage();
if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://"))
imageUrl = "http://" + imageUrl;
Button button = (Button)rowView.findViewById(R.id.condividi);
final String finalImageUrl = imageUrl;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TEXT, web.get(position).getTitle());
File file = writebitmaptofilefirst("the image", finalImageUrl );
Uri path = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, path );
Intent send = Intent.createChooser(intent, null);
context.startActivity(send);
}
});
public static File writebitmaptofilefirst(String filename, String source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
URL url = new URL(source);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
EDIT
String imageUrl = web.get(position).getImage();
if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://"))
imageUrl = "http://" + imageUrl;
Button button = (Button)rowView.findViewById(R.id.condividi);
final String finalImageUrl = imageUrl;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_TEXT, web.get(position).getTitle());
String file = writebitmaptofilefirst("ndp_image", finalImageUrl);
//Uri path = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM, file );
Intent send = Intent.createChooser(intent, null);
context.startActivity(send);
}
});
return rowView;
}
public static String writebitmaptofilefirst(String filename, String source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images/");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
URL url = new URL(source);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file.getAbsolutePath();
}
Add permissions to your manifest
Remove space from file name (the image). With space you need decode the uri. You should paass the full path return file.getAbsolutePath(). You are just passing the file name.
In the case of file exists your not storing in the same path. You were not included the dictionary. extranlstoragepath+/temp_images/+the image.jpg try to log your file paths. And
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
You have missed a / between two paramaters.
Wonderful blogpost about storing image
I am building an android app that accesses the camera but i am wanting to save the image into a specific folder but i have no idea how to go about it. do i use a URI builder?
this is the code i have to get the image from the camera.
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment
.DIRECTORY_PICTURES), "pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
You can create a file from your own directory like this:
private File openFileFromMyDirectory() {
File imageDirectory = null;
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
imageDirectory = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "com.myapp.camera");
if (!imageDirectory.exists() && !imageDirectory.mkdirs()) {
imageDirectory = null;
} else {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
return new File(imageDirectory.getPath() +
File.separator + "IMG_" +
dateFormat.format(new Date()) + ".jpg");
}
}
return null;
}
Then get bitmap from uri:
Bitmap mCameraBitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
Finally save the bitmap into the file
private void saveImageToFile(File file) {
if (mCameraBitmap != null) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
if (!mCameraBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)) {
Toast.makeText(this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Saved image to: " + file.getPath(),
Toast.LENGTH_LONG).show();
}
outStream.close();
} catch (Exception e) {
Toast.makeText(this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
}
}
}
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(MainActivity.this,"Photo disimpan",Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this,"Photo disimpan: " + uriTarget.toString(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}};
How do I save images in the format "2014-04-07-04.jpg" to the SD card?
Try out below code.
private File createImageFile() throws IOException{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, storageDir);
return image;
}
I find a solution is like this:
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d(MakePhotoActivity.DEBUG_TAG, "Can't create directory to save image.");
Toast.makeText(context, "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
} catch (Exception error) {
Log.d(MakePhotoActivity.DEBUG_TAG, "File" + filename + "not saved: "
+ error.getMessage());
Toast.makeText(context, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
private File getDir() {
File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CameraAPIDemo");
}
i'm using the following code for saving the image
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
// File root = Environment.getExternalStorageDirectory();
// File file = new File(root, "androidlife.jpg");
// File file = new File(Environment.getExternalStorageDirectory()
// + File.separator + "/test.jpg");
Random fCount = new Random();
// for (int i = 0; i < 10; i++) { Comment by Lucifer
int roll = fCount.nextInt(600) + 1;
//System.out.println(roll);
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(roll) +".jpg" );
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// } Comment by Lucifer
it save the image perfectly but overwrite when i press the save button twice...What can be the issue? Any sugestion??
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
You have given a static file name.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test.jpg");
So, Everytime it is going to create a image with test.jpg name and at a same location. The only logic you need to implement is to change your file name to be a dynamic file name. You can try it in this way
static int fCount = 0;
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/test" + String.valueOf(fCount++) +".jpg" );
Now above line is going to create a new file every time, starting with name test0.jpg, test1.jpg ... and so on.
But this could create a problem when you close your application and restart your application. Because it will going to start again from 0 counter.
So i suggest you to go with a random number contacatination with file name.
sticker_view.setLocked(true);
sticker_view.setDrawingCacheEnabled(true);
Bitmap bitmap = sticker_view.getDrawingCache();
Log.e("BITMAP", "onOptionsItemSelected: " + bitmap);
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Edited Image");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String photoName = "Image-" + n + ".jpg";
Log.e("PHOTONAME", "onOptionsItemSelected: " + photoName);
File file = new File(newDir, photoName);
String filePath = file.getAbsolutePath();
Log.e("FILEPATH", "onOptionsItemSelected: " + filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(EditActivity.this, "Image Already Exist.", Toast.LENGTH_SHORT).show();
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(file);
Log.e("OUT", "onOptionsItemSelected: " + out);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
bitmap.recycle();
Toast.makeText(EditActivity.this, "Saved In Edited Image.", Toast.LENGTH_SHORT).show();
item.setVisible(false);
MediaScannerConnection.scanFile(EditActivity.this, new String[]{file.getAbsolutePath()},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Intent intent = new Intent();
intent.setAction("URI");
intent.putExtra("uri", filePath);
sendBroadcast(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
You can just add System.currentTimeMillis() in the name of your file name to get a complete unique file name. This will add current time in milliseconds since epoch to your file name and unless you can create more than one file in a single millisecond, no overwrite will be done.