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"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.