I am making a framer app which can be used to frame your image. And i Want to save that image in gallery after framing and for this i have set a button to perform this but in the button by below code i am unable to save my image. After clicking on button it crashes the app activity. please Someone Give me Solution. I am using api level >29.
``` dlbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OutputStream outputStream;
BitmapDrawable drawable = (BitmapDrawable) mainimg.getDrawable();
Bitmap bitmap = drawable.getBitmap();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
{
ContentResolver resolver = MainActivity2.this.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME,"Image_"+".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE,"image/jpeg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_PICTURES + File.separator+"TestFolder");
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
try {
outputStream = resolver.openOutputStream(Objects.requireNonNull(imageUri) );
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
Objects.requireNonNull(outputStream);
Toast.makeText(MainActivity2.this, "Image Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(MainActivity2.this, "Image Not Not Saved: \n "+e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
});
} ``
Related
I stored url with id in firebase. I am using viewpager2 in xml. I want to share image or want to add share option in that. How can I do this.
public void onApplyImage(int position, Bitmap bitmap) {
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toast.makeText(SwiperActivity.this, "Wallpaper successfully set ", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(SwiperActivity.this, "Failed to set as wallpaper", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onShareImage(int position, Bitmap bitmap) {
}
});
Simple way to share is that first set you image to a ImageView and then use the following code to share you image.
ImageView content = (ImageView)mView.findViewById(R.id.imageViewy);
content.setDrawingCacheEnabled(true);
Uri imageUri= Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),
content, "title", "discription"));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
I tried a code to take screenshot of an Activity then share it , which is works very well but just in Android lower than 6.0 , from 6.0 and higher when i click share button then choose social network a short dialog tell me " unable to load image "
Please i need your help my friends
This the code that i used it :
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
shareIt();
}
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
Uri uri = Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
displayResults();
}
EDIT :
I try to replace Uri uri = Uri.fromFile(imagePath); by Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".my.package.name.provider", imagePath);
But it says app was stopped when i click Share button
Any help pleaaaase
If FileUriExposedException is the exception that is the cause for the issue:-
This exception is thrown when an application exposes a file:// Uri to another app.
This is only thrown for applications targeting Build.VERSION_CODES.N or higher. Applications targeting earlier SDK versions are allowed to share file:// Uri, but it's strongly discouraged.
These links might give a detailed answer to the above problem:-
https://developer.android.com/reference/android/os/FileUriExposedException
android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
Hope this helps.
I'm trying to include image sharing in my application and everything is working but the share chooser takes long time to appear on devices
here is what i'm doing:
I have ImageView "items_details_image" and I want to share its image to be able to send it through whatsapp and other apps
void ShareImg() {
try {
Uri bmpUri = getLocalBitmapUri(items_details_image);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
} catch (Exception e) {
}
}
here is how I get bitmap from Image URL
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
I don't know why it is taking longer than usual comparing it with other apps on the same device such as gallery or whatever
You are doing disk I/O on the main application thread, in getLocalBitmapUri(). This will freeze your UI as long as it takes to write your bitmap to disk.
I have integrated crop image library in my application which have function for take and use picture taken via camera. My developer have done it as expected but now when I have checked via take picture from camera than after take picture and set it on crop page, its getting blur before we set it.My developer is out of coverage for some task. I have asked library developer and they have given me solution for integrate code like below
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);Uri outputFileUri = Uri.fromFile(new File(context.getExternalCacheDir().getPath(), "pickImageResult.jpeg"));intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
and My developer have integrated code like below in my application
#Override
public void onClick(DialogInterface dialog, int which) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent,REQ_PHOTO_CAMERA);
}
}
as well method like below
public final int REQ_PHOTO_CAMERA=243;
public final int REQ_PHOTO_GALLERY=346;
public final int REQ_APP_GALLERY=427;
public final int ACTION_CHANGE_BACKGROUND=1;
public final int ACTION_CHANGE_AUTHOR=2;
private int mChangeAction;
public void onActivityResult(int req,int res,Intent data){
if(res==RESULT_OK){
if(req==REQ_PHOTO_CAMERA){
Bitmap cameraImg = (Bitmap) data.getExtras().get("data");
cropAndSaveImage(cameraImg);
//updateCustomImage(cameraImg);
}else if(req==REQ_PHOTO_GALLERY){
try {
Bitmap imgGallery = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
// updateCustomImage(imgGallery);
cropAndSaveImage(imgGallery);
} catch (IOException e) {
// e.printStackTrace();
}
}else if (req == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri resultUri = result.getUri();
Log.e("ImageUrl",resultUri.getPath());
updateCustomImage(BitmapFactory.decodeFile(resultUri.getPath()));
}else if(req==REQ_APP_GALLERY){
String imgPath=data.getStringExtra("ImagePath");
try {
InputStream inputStream=getAssets().open(imgPath);
Bitmap image=BitmapFactory.decodeStream(inputStream);
cropAndSaveImage(image);
} catch (IOException e) {
}
}
}
}
public void cropAndSaveImage(Bitmap imgPicked){
ImageLoader.getInstance().saveTempImage(imgPicked);
CropImage.activity(ImageLoader.getInstance().getTempImageUri())
.setInitialCropWindowPaddingRatio(0)
.setFixAspectRatio(false)
.setAspectRatio(1,2)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
let me know what I am missing ?
Note : we have used this library : Link
Thanks
Your original image taken using camera will be here-
Uri outputFileUri = Uri.fromFile(new File(context.getExternalCacheDir().getPath(), "pickImageResult.jpeg"));
in this file.
the Bitmap cameraImg = (Bitmap) data.getExtras().get("data"); is just a thumbnail returned.
I had a problem when saving picture on sdcard from my app.
that when i am taking a picture and saving it on sdcard and go to my app and take a new one and save it on sdcard the previous preview picture appear and when view it on my computer it appear corrupted ?
why this problem ?
public static void save(Bitmap bm, String path) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(new File(path));
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
bm.recycle();
System.gc();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
enter code here
Use this method to store the image and display it.This is used to store the image
//create new directory to store image
File photo = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/files/Receipt");
boolean success = false;
if(!photo.exists())
{
success = photo.mkdirs();
}
//if exists save the image in specified path
if(!success)
{
dbimgguid = UUID.randomUUID();
imagename =dbimgguid.toString();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photo = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/files/Receipt", imagename+".png");
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
imageurl = Uri.fromFile(photo);
startActivityForResult(intent, CAMERA_RECEIPTREQUEST);
}
To view the image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case CAMERA_RECEIPTREQUEST:
if(resultCode== Activity.RESULT_OK)
{
//Toast.makeText(this, "Receipt Image Saved", Toast.LENGTH_SHORT).show();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
ImageView jpgView = (ImageView)findViewById(R.id.imageView1);
Bitmap receipt = BitmapFactory.decodeFile(photo.toString(),options);
jpgView.setImageBitmap(receipt);
}
break;
}
I hope this will help you..
}
Do you have permissions to store to the SD card? I believe you need save and save to sd permissions.