How to share an image from the Internet without saving it? - android

I'm trying to share an image from the internet using share intents. This doesn't work because I think the image needs to be downloaded first:
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
So I'm downloading an image and then sharing it:
#Background
protected void tryToShareImage(Intent intent) {
try {
URL url = new URL(mImageUrl);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
intent.putExtra(Intent.EXTRA_STREAM, getImageUri(mActivity, image));
} catch (Exception e) {
e.printStackTrace();
}
startActivity(Intent.createChooser(intent, "Share using..."));
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
However, there's one problem: the image stays in the gallery after I don't need it anymore.
Question: Is there a way to share an image from the Internet without saving it first?

Related

Share PNG image using Intent (it changes image form png to jpeg)

I want to make a function which share my images using Intent . Problem is; i have png images and when i share images using Intent, it change the format of image form png to jpeg . for example there is no background (transparent) of my image.png when i call intent to share, it changes image background to black and format to image.jpg.
Here is my code
protected void ShareImage( )
{
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
Bitmap imgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image );
String imgBitmapPath= MediaStore.Images.Media.insertImage(getContentResolver(),imgBitmap,"title",null);
Uri imageUri=Uri.parse(imgBitmapPath);
sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(sharingIntent, "Share images to.."));
}
Please Help me to share image without changing its format .. Thanks
MediaStore.Images.Media.insertImage always writes a JPEG. See its implementation.
You can easily adapt its code to write a PNG instead:
private void shareAsPng(Bitmap bitmap, String title)
{
Long now = System.currentTimeMillis() / 1000;
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, title);
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATE_ADDED, now);
values.put(MediaStore.MediaColumns.DATE_MODIFIED, now);
ContentResolver cr = getContentResolver();
Uri uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream os = cr.openOutputStream(uri)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 0, os);
}
catch (IOException e) {
cr.delete(uri, null, null);
return;
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(intent);
}
The compression quality parameter is documented to be ignored for PNG.
I intentionally omitted IS_PENDING because that requires Android 10.
Convert bitmap to Uri
private Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.PNG, 99, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
and add your application manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Wallpaper resolution issue

I am trying to make wallpaper app but I am facing a problem which is the low resolution after setting the wallpaper.
Although the real picture before setting as wallpaper is very high resolution from url.
This is my code:
public void set(View view) {
Toast.makeText(MainActivity.this, "Setting wallpaper", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(getImageUri(this,bitmaptwo), "image/*");
intent.putExtra("Bitmap", "image/*");
startActivity(intent);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 0, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
Try and convert the wallpaper to a vector, it will scale without any loss of resolution
check this out regarding vectors https://developer.android.com/studio/write/vector-asset-studio.html

Share screenshot from internal storage android

I want to share the screenshot that gets stored in internal storage but all I'm getting while sharing is a blank screen. I came to know that another app cannot use ones won app private data. This is the code I have used to save the image :
File path = new File(getApplicationContext().getDir("Default", Context.MODE_ENABLE_WRITE_AHEAD_LOGGING),"myapp");
File directory = new File(path.getAbsolutePath());
directory.mkdirs();
String filename = "myapp.png";
File yourFile = new File(directory, filename);
try
{
FileOutputStream out = new FileOutputStream(yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 90,out);
out.flush();
out.close();
send(yourFile);
}catch (IOException e)
{
e.printStackTrace();
}
And the share intent is:
public void send(File path)
{
Uri uri = Uri.fromFile(path);
Log.d("uri", String.valueOf(path));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My App");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share via"));
}
The path in which the image is getting saved and the value of path is :
/data/user/0/com.sample.myapp/app_Default/myapp/myapp.png
Now how would I make sure that the screenshot is getting accessed and made available for sharing.
You are getting image URI not Real Image path
to get Real path check this
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
just pass this image uri and get full image path
I solved it by exporting the image to external storage and then sharing.
String url = null;
try {
url = MediaStore.Images.Media.insertImage(getContentResolver(), path.getAbsolutePath(), path.getName(), path.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Uri uri = Uri.parse(url);

How can I save my bitmap correctly for second time?

I want to save my bitmap to cache directory.
I use this code:
try {
File file_d = new File(dir+"screenshot.jpg");
#SuppressWarnings("unused")
boolean deleted = file_d.delete();
} catch (Exception e) {
// TODO: handle exception
}
imagePath = new File(dir+"screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(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);
}
}
it s working fine. But if I want to save different img to same path, something goes wrong. I mean it is saved to same path but I see it old image, but when I click the image I can see the correct image which I saved second time.
Maybe its come from cache but I do not want to see old image because when I want to share that image with whatsapp old image seen , if i send the image it seems correct.
I want to share saved image on whatsapp like this code:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagePath));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);
How can I fix it?
thanks in advance.
Finally I solved my problem like this:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,bitmap_));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);
v
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "TitleC1", null);
return Uri.parse(path);
}
This is just a guess, but since you save a new image (with the old name, or another, that’s not relevant) you should fire a media scan to that path so that the media provider is updated with new content.
See here:
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, null);
Or even better, wait for the scan to be completed:
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, new OnScanCompletedListener() {
#Override
void onScanCompleted(String path, Uri uri) {
// Send your intent now.
}
});
In any case this should be called after the new file is saved. As I said, I have not tested and this is just a random guess.

take screenshot from layout and share via android

I use below code to take screen shot from my layout and share it via android intent but the captured screen shot in the selected app is not showing any thing.
#Override
public void onClick(View view) {
shareBitmap(this,takeScreenshot());
}
public Bitmap takeScreenshot() {
try{
View rootView = getWindow().getDecorView().findViewById(R.id.lyt_main_report_activity);
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}catch (Exception ex){
ex.printStackTrace();
}
return null;
}
public static void shareBitmap(Context context, Bitmap bitmap){
//save to sd card
try {
File cachePath = new File(context.getCacheDir(), "images");
cachePath.mkdirs(); // don't forget to make the directory
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); // overwrites this image every time
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
//start share activity
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = Uri.fromFile(newFile); //FileProvider.getUriForFile(context, "com.persianswitch.apmb.app.fileprovider", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
//shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
// shareIntent.setDataAndType(contentUri, context. getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.setType("image/*");
context.startActivity(Intent.createChooser(shareIntent, context.getResources().getString(R.string.share_using)));
}
}catch (Exception ex){
ex.printStackTrace();
}
}
Please use this code this is tested code :
public static void takeScreenshot(Context context, View view) {
String path = Environment.getExternalStorageDirectory().toString() +
"/" + "test.png";
View v = view.findViewById(android.R.id.content).getRootView();
v.setDrawingCacheEnabled(true);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
} catch (FileNotFoundException e) {
// manage exception
} catch (IOException e) {
// manage exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {}
}
// onPauseVideo();
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
share.setType("image/png");
((Activity) context).startActivityForResult(
Intent.createChooser(share, "Share Drawing"), 111);
}
Since DrawingCache() deprecated above 28 so using Canvas will sort the issues for many. below answer can be used for share Screenshot including text without requesting for permissions.
To take the Screenshot
private Bitmap takeScreenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
To share the Screenshot
private void shareContent(Bitmap bitmap) {
String bitmapPath = MediaStore.Images.Media.insertImage(
binding.getRoot().getContext().getContentResolver(), bitmap, "title", "");
Uri uri = Uri.parse(bitmapPath);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "App");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Currently a new version of KiKi app is available.");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
binding.getRoot().getContext().startActivity(Intent.createChooser(shareIntent, "Share"));
}
if nothing happens it means your Bitmap is null kindly check that. or you could also fall on View.buildDrawingCache(); which will draw the View to Bitmap and then call your View.getDrawingCache();
also When hardware acceleration is turned on, enabling the drawing cache has no effect on rendering because the system uses a different mechanism for acceleration which ignores the flag. If you want to use a Bitmap for the view, even when hardware acceleration is enabled, see setLayerType(int, android.graphics.Paint) for information on how to enable software and hardware layers.
the quote was taken from the documented page
hope it helps
Tipp:The checked answer works when your device has external storage. On the Samsung 6 for example, it doesnt. Therefore you need to work with fileprovider.
Just incase somebody fell into this trap like me. The problem is that you are putting the name of the image twice.
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png");
and than again.
File newFile = new File(imagePath, "image.png");
Change The seconed one to
File newFile = new File(imagePath);
Otherwise the contentUri give you the bitmap of your screenshot. I hope this helps someone. Took me 3 hours to figure it out :)

Categories

Resources