Sharing image failed - android

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

Related

unable to save image to gallery from ImageView in Android

Facing problem in saving image to gallery from webview.....storage permission is granted but it does not work.... i have tried all that i can do...kindly help me
here is the code below
private void saveImageToExternalStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/ahmed");
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);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
MediaScannerConnection.scanFile(getActivity(), new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
And this is the button onClick()
cvDownload.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
anImage = ((BitmapDrawable) ivPhoto.getDrawable()).getBitmap();
saveImageToExternalStorage(anImage);
Toast.makeText(getContext(), "Download successfuly"+anImage.toString(),
Toast.LENGTH_SHORT).show();
}
});
it is work for me:
public void onCreate(){
File path=saveBitmap(bitmap);
MediaScannerConnection.scanFile(this, new String[]{path.getPath()}, new String[]{"png", "jpg"}, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(path)));
startActivity(intent); /** replace with your own uri */
// finish();
// finishAffinity();
}
});
}
public static File saveBitmap(Bitmap bitmap) {
String fileName = "";
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/MyImages");
dir.mkdirs();
fileName = String.format("%d.jpeg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
Follow this code to download image from the ImageView:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
val bitmap = imageView.getDrawable().toBitmap()
var outStream: FileOutputStream? = null
val sdCard: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
val dir = File(sdCard.getAbsolutePath().toString() + "/sastana")
dir.mkdirs()
val fileName = String.format("%d.jpg", System.currentTimeMillis())
val outFile = File(dir, fileName)
outStream = FileOutputStream(outFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
outStream.flush()
outStream.close()
Toast.makeText(this, "Saved Successfully", Toast.LENGTH_SHORT).show()
} catch (e : Exception) {
Log.e("qrcode", e.toString())
}
} else {
Log.e("qrcode", "permission not granted")
}

convert the bitmap file (of a cuptured image) to a path file

the photo parameter is the bitmap and i checked it and it shows the cuptured image
how can i convert the bitmap to path so i will able to send as an attachment to mail
this is the code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.opencvhc);
ImgPhoto = (ImageView) findViewById(R.id.ImgPhoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
bm = (BitmapDataObject) getIntent().getSerializableExtra("photo"); //Obtaining data
bitmap = bm.getBip();
ImgPhoto.setImageBitmap(bitmap);
}
Checkmood = (Button) findViewById(R.id.Checkmood);
Check = (Button) findViewById(R.id.Check);
txtView = (TextView) findViewById(R.id.txt);
}
public void CheckClick(View view) throws IOException {
String file = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "file", null);
//Uri screenshotUri = Uri.parse(file);
Toast.makeText(OpenCVhc.this, file, Toast.LENGTH_SHORT).show();
final Intent emailIntent1 = new Intent(android.content.Intent.ACTION_SEND);
emailIntent1.putExtra(Intent.EXTRA_EMAIL, new String[]{"comfplatform#gmail.com"});
emailIntent1.putExtra(Intent.EXTRA_SUBJECT, "Image processing picture");
emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// emailIntent1.putExtra(Intent.EXTRA_STREAM, screenshotUri);
emailIntent1.putExtra(Intent.EXTRA_TEXT, "" +
"We checked your photo with the Ecg-Leads \n 1) : " +
"\n the image proccessing ___ ");
emailIntent1.setType("image/png");
try {
startActivity(Intent.createChooser(emailIntent1, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(OpenCVhc.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
See this solution and don't forget to check for "WRITE_EXTERNAL_STORAGE" permission before writing to file.
Reference : Android: Saving Bitmap to External Memory
public void saveImageToExternalStorage(Bitmap finalBitmap) {
String root =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).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 file1 = new File(myDir, fname);
if (file1.exists())
file1.delete();
try {
FileOutputStream out = new FileOutputStream(file1);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file1.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}

Android Studio save image into new directory [duplicate]

I need to save the pictures taken with my app in an specific folder. I've read many solutions to this problem but I couldn't make any of them work so I ask for help.
MainActivity.java
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Folder is already created
String dirName = Environment.getExternalStorageDirectory().getPath()
+ "/MyAppFolder/MyApp" + n + ".png";
Uri uriSavedImage = Uri.fromFile(new File(dirName));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
n++;
}
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Go through the following code , its working fine for me.
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File("/sdcard/DirName/", fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have used mdDroid's code like this:
public void startCamera() {
// Create photo
newPhoto = new Photo();
newPhoto.setName(App.getPhotoName());
//Create folder !exist
String folderPath = Environment.getExternalStorageDirectory() + "/PestControl";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdirs();
}
//create a new file
newFile = new File(folderPath, newPhoto.getName());
if (newFile != null) {
// save image here
Uri relativePath = Uri.fromFile(newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
Use Like this. It will work for you.
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
filename= f.getName();
Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
cursor.close();
//Convert file path into bitmap image using below line.
// yourSelectedImage = BitmapFactory.decodeFile(filePath);
Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
//put bitmapimage in your imageview
//yourimgView.setImageBitmap(yourSelectedImage);
Savefile(filename,filePath);
}
}
}
public void Savefile(String name, String path) {
File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");
if(!direct.exists()) {
direct.mkdir();
}
if (!file.exists()) {
try {
file.createNewFile();
FileChannel src = new FileInputStream(path).getChannel();
FileChannel dst = new FileOutputStream(file).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help you. for reference to use camera intent.
Here You Go. I tried the above solution they save the image to gallery but the image is not visible , a 404 error is visible on the image , and i figured it out .
public void addToFav(String dirName, Bitmap bitmap) {
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
dirName + System.currentTimeMillis() + ".jpg";
Log.e("resultpath",resultPath);
new File(resultPath).getParentFile().mkdir();
if (Build.VERSION.SDK_INT < 29){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
if(fileOutputStream != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}else {
OutputStream fos = null;
File file = new File(resultPath);
final String relativeLocation = Environment.DIRECTORY_PICTURES;
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation+"/"+dirName);
contentValues.put(MediaStore.MediaColumns.TITLE, "Photo");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis ());
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
contentValues.put(MediaStore.MediaColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
contentValues.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
final ContentResolver resolver = getContentResolver();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = resolver.insert(contentUri, contentValues);
try {
fos = resolver.openOutputStream(uri);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fos != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
}
}
I have found an easier code to do it.
This is the code for creating the image folder:
private File createImageFile(){
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/App Folder/";
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "AppName_" + timeStamp;
String file = dir +imageFileName+ ".jpg" ;
File imageFile = new File(file);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
}
,And this is the code for launching the camera app and take the photo:
public void lunchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = createImageFile();
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.ziad.sayit",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Useful link for different ways of doing it: https://www.programcreek.com/java-api-examples/?class=android.os.Environment&method=getExternalStoragePublicDirectory

Android - Save images in an specific folder

I need to save the pictures taken with my app in an specific folder. I've read many solutions to this problem but I couldn't make any of them work so I ask for help.
MainActivity.java
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Folder is already created
String dirName = Environment.getExternalStorageDirectory().getPath()
+ "/MyAppFolder/MyApp" + n + ".png";
Uri uriSavedImage = Uri.fromFile(new File(dirName));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
n++;
}
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Go through the following code , its working fine for me.
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/DirName/");
wallpaperDirectory.mkdirs();
}
File file = new File("/sdcard/DirName/", fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have used mdDroid's code like this:
public void startCamera() {
// Create photo
newPhoto = new Photo();
newPhoto.setName(App.getPhotoName());
//Create folder !exist
String folderPath = Environment.getExternalStorageDirectory() + "/PestControl";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdirs();
}
//create a new file
newFile = new File(folderPath, newPhoto.getName());
if (newFile != null) {
// save image here
Uri relativePath = Uri.fromFile(newFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, relativePath);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
Use Like this. It will work for you.
public void onClick(View v) {
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 1:
if(resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
filename= f.getName();
Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
cursor.close();
//Convert file path into bitmap image using below line.
// yourSelectedImage = BitmapFactory.decodeFile(filePath);
Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
//put bitmapimage in your imageview
//yourimgView.setImageBitmap(yourSelectedImage);
Savefile(filename,filePath);
}
}
}
public void Savefile(String name, String path) {
File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/");
File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/MyApp/"+n+".png");
if(!direct.exists()) {
direct.mkdir();
}
if (!file.exists()) {
try {
file.createNewFile();
FileChannel src = new FileInputStream(path).getChannel();
FileChannel dst = new FileOutputStream(file).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope this will help you. for reference to use camera intent.
Here You Go. I tried the above solution they save the image to gallery but the image is not visible , a 404 error is visible on the image , and i figured it out .
public void addToFav(String dirName, Bitmap bitmap) {
String resultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES)+
dirName + System.currentTimeMillis() + ".jpg";
Log.e("resultpath",resultPath);
new File(resultPath).getParentFile().mkdir();
if (Build.VERSION.SDK_INT < 29){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Photo");
values.put(MediaStore.Images.Media.DESCRIPTION, "Edited");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put("_data", resultPath);
ContentResolver cr = getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream fileOutputStream = new FileOutputStream(resultPath);
bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
if(fileOutputStream != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}else {
OutputStream fos = null;
File file = new File(resultPath);
final String relativeLocation = Environment.DIRECTORY_PICTURES;
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation+"/"+dirName);
contentValues.put(MediaStore.MediaColumns.TITLE, "Photo");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, System.currentTimeMillis ());
contentValues.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
contentValues.put(MediaStore.MediaColumns.BUCKET_ID, file.toString().toLowerCase(Locale.US).hashCode());
contentValues.put(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME, file.getName().toLowerCase(Locale.US));
final ContentResolver resolver = getContentResolver();
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Uri uri = resolver.insert(contentUri, contentValues);
try {
fos = resolver.openOutputStream(uri);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fos != null){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
}
}
I have found an easier code to do it.
This is the code for creating the image folder:
private File createImageFile(){
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/App Folder/";
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "AppName_" + timeStamp;
String file = dir +imageFileName+ ".jpg" ;
File imageFile = new File(file);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
}
,And this is the code for launching the camera app and take the photo:
public void lunchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = createImageFile();
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.ziad.sayit",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
Useful link for different ways of doing it: https://www.programcreek.com/java-api-examples/?class=android.os.Environment&method=getExternalStoragePublicDirectory

Attach image from resource with Email Body Android

I have an app in which there is an email section where I have to entered text and image in body. I searched on net but did not find corresponding solution. Any help will would be appreciated.
Here is the View :
BitmapFactory.Options bitmapFatoryOptions=new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;
Bitmap myBitmap=BitmapFactory.decodeResource(getResources(),R.drawable.face4,bitmapFatoryOptions);
File mFile = savebitmap(myBitmap);
Uri u = null;
u = Uri.fromFile(mFile);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("image/*");
Intent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Send Mail");
emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_texthere));
emailIntent.putExtra(Intent.EXTRA_STREAM, u);
startActivity(Intent.createChooser(emailIntent,"Send"));
Code for saveBitmap() Method:
private File savebitmap(Bitmap bmp) {
String temp="SplashItShare";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
String path = Environment.getExternalStorageDirectory()
.toString();
new File(path + "/SplashItTemp").mkdirs();
File file = new File(path+"/SplashItTemp", temp + ".png");
if (file.exists()) {
file.delete();
file = new File(path+"/SplashItTemp", temp + ".png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
Hope It will work for you.

Categories

Resources