how to save photo from image view to gallerry android xamarin - java

hello i'm newbie in xamarin ,I try to find a lot code of internet but it won't work.
In my imageview have dot menu, When user click on menu in imageview they can forword photo or share photo but can't save.
I want to add save photo function in there , but no idea , This is part of my code to share and forward
public async void OnSelection(MaterialDialog dialog, View itemView, int position, string itemString)
{
try
{
if (itemString == GetText(Resource.String.Lbl_MessageInfo))
{
var intent = new Intent(this, typeof(MessageInfoActivity));
intent.PutExtra("UserId", Id);
intent.PutExtra("MainChatColor", !string.IsNullOrEmpty(MesData.ChatColor) ? MesData.ChatColor : AppSettings.MainColor ?? AppSettings.MainColor);
intent.PutExtra("SelectedItem", JsonConvert.SerializeObject(MesData));
StartActivity(intent);
}
else if (itemString == GetText(Resource.String.Lbl_Forward))
{
var intent = new Intent(this, typeof(ForwardMessagesActivity));
intent.PutExtra("SelectedItem", JsonConvert.SerializeObject(MesData));
StartActivity(intent);
}
else if (itemString == GetText(Resource.String.Lbl_Share))
{
string urlImage = MediaFile;
var fileName = urlImage?.Split('/').Last();
await ShareFileImplementation.ShareRemoteFile(urlImage, urlImage, fileName, GetText(Resource.String.Lbl_SendTo));
}
catch (Exception e)
{
Methods.DisplayReportResultTrack(e);
}
}

The following code used to work before Android10.0(Android Q) .
//get the data
ImageView image = FindViewById<ImageView>(Resource.Id.image);
Bitmap bitmap = ((BitmapDrawable)image.Drawable).Bitmap;
MemoryStream baos = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
imageInByte = baos.ToArray();
//store it in gallery
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), "abc.png");
System.IO.File.WriteAllBytes(path, imageInByte);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
this.SendBroadcast(mediaScanIntent);
However , GetExternalStoragePublicDirectory is deprecated from Android Q ,It seems that since Android 11 we can't write file into public external storage including gallery , it is only allowed to place file in app's own isolated shared storage.
Refer to docs :
https://developer.android.com/reference/android/os/Environment#getExternalStoragePublicDirectory(java.lang.String).

Related

How to share Screenshot of current page by using intent?

I am developing and android blog application where I want to share my current blog page screenshot.I try but it showing file format is not supported..please help me to find my error..Thanks in advance
MyAdapter.java
sendImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap app_snap = ((BitmapDrawable)movie_image.getDrawable()).getBitmap();
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SaveImg";
System.out.println("****FILEPATH **** : " + file_path);
File imagePath = new File(Environment.getExternalStorageDirectory() + "/scr.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
System.out.println("****FILEPATH1 **** : " + file_path);
app_snap.compress(Bitmap.CompressFormat.PNG, 200, fos);
System.out.println("****FILEPATH2 **** : " + file_path);
fos.flush();
fos.close();
}
catch (IOException e) {
System.out.println("GREC****** "+ e.getMessage());
}
Intent sharingIntent = new Intent();
Uri imageUri = Uri.parse(imagePath.getAbsolutePath());
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
context.startActivity(sharingIntent);
}
});
Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:
First, you need to add a proper permission to save the file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
If you want to use this on fragment view then use:
View v1 = getActivity().getWindow().getDecorView().getRootView();
instead of
View v1 = getWindow().getDecorView().getRootView();
on takeScreenshot() function
Note:
This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:
Android Take Screenshot of Surface View Shows Black Screen
if u have any doubt please go through this link
You can get the Bitmap of your screen view inside your layouts. Where view will be your layout views like Linear or RelativeLayout
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap returnedBitmap = view.getDrawingCache();
then have to convert into byte[] so that you can send with the Intent like this following:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
returnedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
and send data with Intent like this:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("bitmap_",byteArray);
get Intent on your SecondActivity like this:
byte[] byteArray = getIntent().getByteArrayExtra("bitmap_");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

Sending picture through intent and display into PDF

I have three Activities
Hobbies
Language
Add Photo
What my goal: I get value of the hobby and language activity and also photo one and send it to the other activity and with that knowledge i create PDF file
Problem since i have 3 activities if user first go to Hobby activity and fill fields and then go to the language activity and fill all fields and at the end user go to the photo activity and fetch the photo from phone media and then create PDF file by doing this way I get the data as well as picture in PDF .Here my code works perfect USER SELECT PHOTO AT THE END AFTER FILLING DATA IN OTHER ACTIVITIES but Problem occur when and if he selects image first and then fills data and create PDF what happens I only get data in my PDF no sign of picture !!
I wanna put all the code but that too much code
Sending picture
private void getting_data_from_fields_and_sending_on_click_listner() {
Intent i = new Intent (Add_Picture_Activity.this , Selecting_Activity.class) ;
ByteArrayOutputStream b = new ByteArrayOutputStream() ;
resultBmp.compress(Bitmap.CompressFormat.JPEG , 100 , b);
byte[] bytes = b.toByteArray();
i.putExtra("UserImage" , bytes);
startActivity(i);
}
receiving Picture
public void gettingInfoFromTheAddPictureActivity() {
bitmap = (Bitmap) getIntent().getParcelableExtra("UserImage");
byte [] bytes = getIntent().getByteArrayExtra("UserImage");
bitmap = BitmapFactory.decodeByteArray(bytes , 0 , bytes.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG , 100 , stream);
userImage = null ;
try {
userImage = Image.getInstance(stream.toByteArray());
}catch (Exception c){
}
}
try {
gettingInfoFromTheAddPictureActivity();
userImage.scaleToFit(80 , 80);
userImage.setAbsolutePosition(0,0) ;
p.getDirectContent();
document.add(userImage);
}catch (Exception x){
}
Some How i solved the problem
First i get the path of the user selected image and store it in pref and then use that path to create a bitmap in other activity and then with the bitmap i load image to the PDF File ..
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri imageUri = data.getData( );
picturePath = getPath( Add_Picture_Activity.this, imageUri );
Log.d("Picture Path", picturePath);
}else{
Toast.makeText(this, "You have not select image", Toast.LENGTH_SHORT).show();
}
}
public static String getPath(Context context, Uri uri ) {
String result = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
if(cursor != null){
if ( cursor.moveToFirst( ) ) {
int column_index = cursor.getColumnIndexOrThrow( proj[0] );
result = cursor.getString( column_index );
}
cursor.close( );
}
if(result == null) {
result = "Not found";
}
return result;
}
private void getting_data_from_fields_and_sending_on_click_listner() {
Intent sendingPicPath = new Intent (Add_Picture_Activity.this , Selecting_Activity.class);
editor = pref.edit() ;
editor.putString("IMAGEPATH" , picturePath);
editor.apply();
startActivity(sendingPicPath);
}
on other activity
String imagePath = user_image.getString("IMAGEPATH" ,"");
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

Adding HashMap to marker to display image doesn't return the correct image for that specific marker

I am going to try and explain this in much detail as possible (if i miss anything please let me know)
So in my app on the map the user can longclick at any point on the map, which then adds a default marker and it starts the camera intent, whereby the user can take a photo of the castle and return to the map. so when the user then taps on the map the full image is displayed in the getInfoContents(Marker marker) and when the user taps on the infoWindow they can either select "delete marker" or "cancel" All of this is fine and working. However the problem i am facing is when the user takes a photo of castle 1 and places the marker, and then take another photo of castle 2 and places the marker, what seem to happen is that when tapping on castle 1 marker, castle 2 image is displayed (the same then for castle 2)
So what i would like to do is "save" that image to that specific marker.
So this is my code up until this point:
I created the HashMap:
private HashMap<Bitmap, Marker> myMarkersHash;
Then in onCreate method this:
myMarkersHash = new HashMap<Bitmap, Marker>();
Then in onMapLongClick this:
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(thePoint));
myMarkersHash.put(bitmap, marker);
Then in my getInfoContents(Marker marker) this:
View v = getLayoutInflater().inflate(R.layout.infowindow_layout, null);
final ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);
myMarkersHash.get(bitmap);
markerIcon.setImageBitmap(bitmap);
But this doesn't seem to work, so am missing something here I think.
This is my camera intent (Might help with my question)
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "My Castle");
imagesFolder.mkdirs();
image = new File(imagesFolder, "Mycastle_" + timeStamp + ".jpg");
fileUri = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(imageIntent, TAKE_PICTURE);
Then in onActivityResult this:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
try {
GetImageThumbnail getImageThumbnail = new GetImageThumbnail();
bitmap = getImageThumbnail.getThumbnail(fileUri, this);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
(Just to add the onActivityResult gets the scaled down image from the GetImageThumbnail.class
Hope i have made sense and really hoping some one could assist me with this problem.
Thank you in advance!
EDIT 1
So what i have tried now is to implement this:
private Map<String, Uri> myMarkersHash;
the in onCreate Method:
myMarkersHash = new HashMap<String, Uri>();
Then in onMapLongClick this:
myMarkersHash.put(marker.getId(), fileUri );
And finally getInfoContents this:
myMarkersHash.get(marker.getId() + fileUri);
markerIcon.setImageBitmap(bitmap);
But unfortunately it still doesn't seem to work. I have also tried image.getAbsolutePath(); but that just crashes the app with a nullPointerException
EDIT 2
As suggested i have tried this:
private Map<String, Bitmap> myMarkersHash;
the in onCreate Method:
myMarkersHash = new HashMap<String, Bitmap>();
Then in onMapLongClick this:
myMarkersHash.put(marker.getId(), bitmap);
And finally getInfoContents this:
myMarkersHash.get(marker.getId());
markerIcon.setImageBitmap(bitmap);
But still doesn't seem to work, still displaying the same image for every marker. I think that it doesn't see that image taken at that point (although the images are saved to a folder on the sdCard if that makes sense?)
EDIT 3
Okay so there is light at the end of the tunnel! However not quite there yet. As suggested i have implemented this code:
Bitmap bitmap = myMarkersHash.get(marker.getId());
markerIcon.setImageBitmap(bitmap);
Now what seems to happen is this:
a. 1st marker placed = no image
b. 2nd marker placed = image of the first marker
c. 3rd marker placed = image of the 2nd marker
d. 4th marker placed = image of the 3rd marker
e. 5th marker placed = image of the 4th marker
and so forth.
Any ideas why this would happen? Will try something now and let you know.
EDIT 4
Full OnMapLongClick code:
#Override
public void onMapLongClick(LatLng point) {
thePoint=point;
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(thePoint));
myMarkersHash.put(marker.getId(), bitmap );
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "My Castle");
imagesFolder.mkdirs();
image = new File(imagesFolder.getPath(), "Mycastle_" + timeStamp + ".jpg");
fileUri = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(imageIntent, TAKE_PICTURE);
}
Hope this helps.
EDIT 5
GREAT!! it works!! Whoop, but the problem is it is turning an image taken in portrait to landscape, which is why i had to implement this code:
ExifInterface exif = null;
try {
exif = new ExifInterface(image.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
if (orientation != 1) {
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
default:
rotate = 0;
break;
}
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
}
But since adding the code as suggested, its gone back to displaying the photo taken in portrait to landscape.
LAST EDIT
Okay so all is working now a 100%!! Thanks for all the help, much appreciated!!!
I am not sure from your edit of what you are exactly doing, but it seems you're not using HashMap as you would need to. You might try something like this:
Bitmap bitmap = myMarkersHash.get(marker.getId());
markerIcon.setBitmap(bitmap);
You should also create a local bitmap before adding it to the HashMap:
#Override
public void onMapLongClick(LatLng point) {
thePoint=point;
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(thePoint));
markerId = marker.getId();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "My Castle");
imagesFolder.mkdirs();
image = new File(imagesFolder.getPath(), "Mycastle_" + timeStamp + ".jpg");
fileUri = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(imageIntent, TAKE_PICTURE);
}
Then when you set your bitmap:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
try {
GetImageThumbnail getImageThumbnail = new GetImageThumbnail();
Bitmap bitmap = getImageThumbnail.getThumbnail(fileUri, this);
myMarkersHash.put(markerId, bitmap );
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Therefore, you need to store your markerId somewhere to be able to get it in onActivityResult
I think you are creating a new imagesFolder every time.
You can try to do something like:
File imagesFolder = new(File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "My Castle");
if (!imagesFolder.exists()) {
if (!imagesFolder.mkdirs()) {
Log.e(TAG, "Fail to create directory.");
return null;
}
}
And this:
file = new File(imageFolder.getPath() + File.seperator + "IMG_" + timestamp + ".jpg");
Also, you can output the list of Marker ID from your hashmap, see if the number of marker ids matched.

how can i take a screen shot of current mobile screen View through Service (background process) Android [duplicate]

How can I take a screenshot of a selected area of phone-screen not by any program but from code?
Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:
First, you need to add a proper permission to save the file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
If you want to use this on fragment view then use:
View v1 = getActivity().getWindow().getDecorView().getRootView();
instead of
View v1 = getWindow().getDecorView().getRootView();
on takeScreenshot() function
Note:
This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:
Android Take Screenshot of Surface View Shows Black Screen
Call this method, passing in the outer most ViewGroup that you want a screen shot of:
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Note: works only for rooted phone
Programmatically, you can run adb shell /system/bin/screencap -p /sdcard/img.png as below
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
then read img.png as Bitmap and use as your wish.
No root permission or no big coding is required for this method.
On adb shell using below command you can take screen shot.
input keyevent 120
This command does not required any root permission so same you can perform from java code of android application also.
Process process;
process = Runtime.getRuntime().exec("input keyevent 120");
More about keyevent code in android see http://developer.android.com/reference/android/view/KeyEvent.html
Here we have used. KEYCODE_SYSRQ its value is 120 and used for System Request / Print Screen key.
As CJBS said, The output picture will be saved in /sdcard/Pictures/Screenshots
Mualig answer is very good, but I had the same problem Ewoks describes, I'm not getting the background. So sometimes is good enough and sometimes I get black text over black background (depending on the theme).
This solution is heavily based in Mualig code and the code I've found in Robotium. I'm discarding the use of drawing cache by calling directly to the draw method. Before that I'll try to get the background drawable from current activity to draw it first.
// Some constants
final static String SCREENSHOTS_LOCATIONS = Environment.getExternalStorageDirectory().toString() + "/screenshots/";
// Get device dimmensions
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
// Get root view
View view = mCurrentUrlMask.getRootView();
// Create the bitmap to use to draw the screenshot
final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_4444);
final Canvas canvas = new Canvas(bitmap);
// Get current theme to know which background to use
final Activity activity = getCurrentActivity();
final Theme theme = activity.getTheme();
final TypedArray ta = theme
.obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);
// Draw background
background.draw(canvas);
// Draw views
view.draw(canvas);
// Save the screenshot to the file system
FileOutputStream fos = null;
try {
final File sddir = new File(SCREENSHOTS_LOCATIONS);
if (!sddir.exists()) {
sddir.mkdirs();
}
fos = new FileOutputStream(SCREENSHOTS_LOCATIONS
+ System.currentTimeMillis() + ".jpg");
if (fos != null) {
if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
Log.d(LOGTAG, "Compress/Write failed");
}
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As a reference, one way to capture the screen (and not just your app activity) is to capture the framebuffer (device /dev/graphics/fb0). To do this you must either have root privileges or your app must be an app with signature permissions ("A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission") - which is very unlikely unless you compiled your own ROM.
Each framebuffer capture, from a couple of devices I have tested, contained exactly one screenshot. People have reported it to contain more, I guess it depends on the frame/display size.
I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480 RGBA (3 279 360 bytes). Yes, the frame, in binary, outputted from fb0 is RGBA in my device. This will most likely depend from device to device. This will be important for you to decode it =)
In my device /dev/graphics/fb0 permissions are so that only root and users from group graphics can read the fb0.
graphics is a restricted group so you will probably only access fb0 with a rooted phone using su command.
Android apps have the user id (uid) = app_## and group id (guid) = app_## .
adb shell has uid = shell and guid = shell, which has much more permissions than an app. You can actually check those permissions at /system/permissions/platform.xml
This means you will be able to read fb0 in the adb shell without root but you will not read it within the app without root.
Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on AndroidManifest.xml will do nothing for a regular app because these will only work for 'signature' apps.
Also check this closed thread for more details.
private void captureScreen() {
View v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
try {
FileOutputStream fos = new FileOutputStream(new File(Environment
.getExternalStorageDirectory().toString(), "SCREEN"
+ System.currentTimeMillis() + ".png"));
bmp.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Add the permission in the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For Supporting Marshmallow or above versions, please add the below code in the activity onCreate method
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},00);
My solution is:
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
and
public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}
Images are saved in the external storage folder.
You can try the following library:
http://code.google.com/p/android-screenshot-library/
Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.
Based on the answer of #JustinMorris above and #NiravDangi here https://stackoverflow.com/a/8504958/2232148 we must take the background and foreground of a view and assemble them like this:
public static Bitmap takeScreenshot(View view, Bitmap.Config quality) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), quality);
Canvas canvas = new Canvas(bitmap);
Drawable backgroundDrawable = view.getBackground();
if (backgroundDrawable != null) {
backgroundDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
return bitmap;
}
The quality parameter takes a constant of Bitmap.Config, typically either Bitmap.Config.RGB_565 or Bitmap.Config.ARGB_8888.
public class ScreenShotActivity extends Activity{
private RelativeLayout relativeLayout;
private Bitmap myBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
relativeLayout.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(relativeLayout);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if(v!=null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
}catch (Exception e){
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
public static void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
}
ADD PERMISSION
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can try to do something like this,
Getting a bitmap cache from a layout or a view by doing something like
First you gotta setDrawingCacheEnabled to a layout(a linearlayout or relativelayout, or a view)
then
Bitmap bm = layout.getDrawingCache()
Then you do whatever you want with the bitmap. Either turning it into an image file, or send the bitmap's uri to somewhere else.
Short way is
FrameLayout layDraw = (FrameLayout) findViewById(R.id.layDraw); /*Your root view to be part of screenshot*/
layDraw.buildDrawingCache();
Bitmap bmp = layDraw.getDrawingCache();
Most of the answers for this question use the the Canvas drawing method or drawing cache method. However, the View.setDrawingCache() method is deprecated in API 28. Currently the recommended API for making screenshots is the PixelCopy class available from API 24 (but the methods which accept Window parameter are available from API 26 == Android 8.0 Oreo). Here is a sample Kotlin code for retrieving a Bitmap:
#RequiresApi(Build.VERSION_CODES.O)
fun saveScreenshot(view: View) {
val window = (view.context as Activity).window
if (window != null) {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val locationOfViewInWindow = IntArray(2)
view.getLocationInWindow(locationOfViewInWindow)
try {
PixelCopy.request(window, Rect(locationOfViewInWindow[0], locationOfViewInWindow[1], locationOfViewInWindow[0] + view.width, locationOfViewInWindow[1] + view.height), bitmap, { copyResult ->
if (copyResult == PixelCopy.SUCCESS) {
saveBitmap(bitmap)
}
// possible to handle other result codes ...
}, Handler())
} catch (e: IllegalArgumentException) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
}
}
}
For those who want to capture a GLSurfaceView, the getDrawingCache or drawing to canvas method won't work.
You have to read the content of the OpenGL framebuffer after the frame has been rendered. There is a good answer here
I have created a simple library that takes a screenshot from a View and either gives you a Bitmap object or saves it directly to any path you want
https://github.com/abdallahalaraby/Blink
If you want to take screenshot from fragment than follow this:
Override onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
mView = view;
}
Logic for taking screenshot:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = mView.findViewById(R.id.scrollView1);
shareScreenShotM(view, (NestedScrollView) view);
}
method shareScreenShotM)():
public void shareScreenShotM(View view, NestedScrollView scrollView){
bm = takeScreenShot(view,scrollView); //method to take screenshot
File file = savePic(bm); // method to save screenshot in phone.
}
method takeScreenShot():
public Bitmap takeScreenShot(View u, NestedScrollView z){
u.setDrawingCacheEnabled(true);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Log.d("yoheight",""+ totalHeight);
Log.d("yowidth",""+ totalWidth);
u.layout(0, 0, totalWidth, totalHeight);
u.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
u.setDrawingCacheEnabled(false);
u.destroyDrawingCache();
return b;
}
method savePic():
public static File savePic(Bitmap bm){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File sdCardDirectory = new File(Environment.getExternalStorageDirectory() + "/Foldername");
if (!sdCardDirectory.exists()) {
sdCardDirectory.mkdirs();
}
// File file = new File(dir, fileName);
try {
file = new File(sdCardDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
file.createNewFile();
new FileOutputStream(file).write(bytes.toByteArray());
Log.d("Fabsolute", "File Saved::--->" + file.getAbsolutePath());
Log.d("Sabsolute", "File Saved::--->" + sdCardDirectory.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
For activity you can simply use View v1 = getWindow().getDecorView().getRootView(); instead of mView
Just extending taraloca's answer. You must add followings lines to make it work. I have made the image name static. Please ensure you use taraloca's timestamp variable incase you need dynamic image name.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private void verifyStoragePermissions() {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}else{
takeScreenshot();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
takeScreenshot();
}
}
}
And in the AndroidManifest.xml file following entries are must:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For Full Page Scrolling Screenshot
If you want to capture a full View screenshot (Which contains a scrollview or so) then have a check at this library
https://github.com/peter1492/LongScreenshot
All you have to do is import the Gradel, and create an object of BigScreenshot
BigScreenshot longScreenshot = new BigScreenshot(this, x, y);
A callback will be received with the bitmap of the Screenshots taken while automatically scrolling through the screen view group and at the end assembled together.
#Override public void getScreenshot(Bitmap bitmap) {}
Which can be saved to the gallery or whatsoever usage is necessary their after
For system applications only!
Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();
Note: System applications don't need to run "su" to execute this command.
The parameter view is the root layout object.
public static Bitmap screenShot(View view) {
Bitmap bitmap = null;
if (view.getWidth() > 0 && view.getHeight() > 0) {
bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
}
return bitmap;
}
From Android 11 (API level 30) you can take screen shot with the accessibility service:
takeScreenshot - Takes a screenshot of the specified display and returns it via an AccessibilityService.ScreenshotResult.
Take screenshot of a view in android.
public static Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
If you want to capture screenshot of a View, use View::drawToBitmap extension function:
val bitmap = myTargetView.drawToBitmap(/*Optional:*/ Bitmap.Config.ARGB_8888)
Only make sure to use the -ktx version of AndroidX Core library:
implementation("androidx.core:core-ktx:1.6.0")
I've already answered a similar question like this here.
Kotlin
private fun screenShot() {
try {
val mPath: String = this.getExternalFilesDir(null).getAbsolutePath()
.toString() + "/temp" + ".png"
// create bitmap screenshot
val v1: View = getWindow().getDecorView().getRootView()
v1.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(v1.drawingCache)
v1.isDrawingCacheEnabled = false
val imageFile = File(mPath)
val outputStream = FileOutputStream(imageFile)
val quality = 100
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream)
outputStream.flush()
outputStream.close()
//or you can share to test the method fast
val uriPath =
FileProvider.getUriForFile(this, getPackageName() + ".sharing.provider", imageFile)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.clipData = ClipData.newRawUri("", uriPath)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
intent.putExtra(Intent.EXTRA_STREAM, uriPath)
startActivity(Intent.createChooser(intent, "Sharing to..."))
} catch (e: Throwable) {
e.printStackTrace()
}
}
Java
private void screenShot() {
try {
String mPath = this.getExternalFilesDir(null).getAbsolutePath().toString() + "/temp" + ".png";
// create bitmap screenshot
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
//or you can share to test the method fast
Uri uriPath = FileProvider.getUriForFile(this, getPackageName() + ".sharing.provider", imageFile);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.setClipData(ClipData.newRawUri("", uriPath));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, uriPath);
startActivity(Intent.createChooser(intent, "Sharing to..."));
} catch (Throwable e) {
e.printStackTrace();
}
}
If you want to capture a view or layout like RelativeLayout or LinearLayout etc.
Just use the code:
LinearLayout llMain = (LinearLayout) findViewById(R.id.linearlayoutMain);
Bitmap bm = loadBitmapFromView(llMain);
now you can save this bitmap on device storage by :
FileOutputStream outStream = null;
File f=new File(Environment.getExternalStorageDirectory()+"/Screen Shots/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "my new screen shot");
pathOfImage = file.getAbsolutePath();
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
addImageGallery(file);
//mail.setEnabled(true);
flag=true;
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
outStream.flush();
outStream.close();
} catch (IOException e) {e.printStackTrace();}

How can I pass a Bitmap object from one activity to another

In my activity, I create a Bitmap object and then I need to launch another Activity,
How can I pass this Bitmap object from the sub-activity (the one which is going to be launched)?
Bitmap implements Parcelable, so you could always pass it with the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.
I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?
Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.
To store bitmap in a file myImage in internal storage:
public String createImageFromBitmap(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
Then in the next activity you can decode this file myImage to a bitmap using following code:
//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));
Note A lot of checking for null and scaling bitmap's is ommited.
If the image is too large and you can't save&load it to the storage, you should consider just using a global static reference to the bitmap (inside the receiving activity), which will be reset to null on onDestory, only if "isChangingConfigurations" returns true.
Compress and Send Bitmap
The accepted answer will crash when the Bitmap is too large. I believe it's a 1MB limit. The Bitmap must be compressed into a different file format such as a JPG represented by a ByteArray, then it can be safely passed via an Intent.
Implementation
The function is contained in a separate thread using Kotlin Coroutines because the Bitmap compression is chained after the Bitmap is created from an url String. The Bitmap creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.
Concepts Used
Kotlin Coroutines notes.
The Loading, Content, Error (LCE) pattern is used below. If interested you can learn more about it in this talk and video.
LiveData is used to return the data. I've compiled my favorite LiveData resource in these notes.
In Step 3, toBitmap() is a Kotlin extension function requiring that library to be added to the app dependencies.
Code
1. Compress Bitmap to JPG ByteArray after it has been created.
Repository.kt
suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
postValue(Lce.Loading())
postValue(Lce.Content(ContentResult.ContentBitmap(
ByteArrayOutputStream().apply {
try {
BitmapFactory.decodeStream(URL(url).openConnection().apply {
doInput = true
connect()
}.getInputStream())
} catch (e: IOException) {
postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
null
}?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
}.toByteArray(), "")))
}
}
ViewModel.kt
//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
when (lce) {
is Lce.Loading -> liveData {}
is Lce.Content -> liveData {
emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
}
is Lce.Error -> liveData {
Crashlytics.log(Log.WARN, LOG_TAG,
"bitmapToByteArray error or null - ${lce.packet.errorMessage}")
}
}
})
}
2. Pass image as ByteArray via an Intent.
In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.
Fragment.kt
ContextCompat.startForegroundService(
context!!,
Intent(context, AudioService::class.java).apply {
action = CONTENT_SELECTED_ACTION
putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
})
3. Convert ByteArray back to Bitmap.
Utils.kt
fun ByteArray.byteArrayToBitmap(context: Context) =
run {
BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
if (this != null) this
// In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
}
}
Because Intent has size limit .
I use public static object to do pass bitmap from service to broadcast ....
public class ImageBox {
public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>();
}
pass in my service
private void downloadFile(final String url){
mExecutorService.submit(new Runnable() {
#Override
public void run() {
Bitmap b = BitmapFromURL.getBitmapFromURL(url);
synchronized (this){
TaskCount--;
}
Intent i = new Intent(ACTION_ON_GET_IMAGE);
ImageBox.mQ.offer(b);
sendBroadcast(i);
if(TaskCount<=0)stopSelf();
}
});
}
My BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LOG.d(TAG, "BroadcastReceiver get broadcast");
String action = intent.getAction();
if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
Bitmap b = ImageBox.mQ.poll();
if(b==null)return;
if(mListener!=null)mListener.OnGetImage(b);
}
}
};
It might be late but can help.
On the first fragment or activity do declare a class...for example
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
description des = new description();
if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
constan.photoMap = bitmap;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class constan {
public static Bitmap photoMap = null;
public static String namePass = null;
}
Then on the second class/fragment do this..
Bitmap bm = postFragment.constan.photoMap;
final String itemName = postFragment.constan.namePass;
Hope it helps.
All of the above solutions doesn't work for me, Sending bitmap as parceableByteArray also generates error android.os.TransactionTooLargeException: data parcel size.
Solution
Saved the bitmap in internal storage as:
public String saveBitmap(Bitmap bitmap) {
String fileName = "ImageName";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
and send in putExtra(String) as
Intent intent = new Intent(ActivitySketcher.this,ActivityEditor.class);
intent.putExtra("KEY", saveBitmap(bmp));
startActivity(intent);
and Receive it in other activity as:
if(getIntent() != null){
try {
src = BitmapFactory.decodeStream(openFileInput("myImage"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can create a bitmap transfer. try this....
In the first class:
1) Create:
private static Bitmap bitmap_transfer;
2) Create getter and setter
public static Bitmap getBitmap_transfer() {
return bitmap_transfer;
}
public static void setBitmap_transfer(Bitmap bitmap_transfer_param) {
bitmap_transfer = bitmap_transfer_param;
}
3) Set the image:
ImageView image = (ImageView) view.findViewById(R.id.image);
image.buildDrawingCache();
setBitmap_transfer(image.getDrawingCache());
Then, in the second class:
ImageView image2 = (ImageView) view.findViewById(R.id.img2);
imagem2.setImageDrawable(new BitmapDrawable(getResources(), classe1.getBitmap_transfer()));
In my case, the way mentioned above didn't worked for me. Every time I put the bitmap in the intent, the 2nd activity didn't start. The same happened when I passed the bitmap as byte[].
I followed this link and it worked like a charme and very fast:
package your.packagename
import android.graphics.Bitmap;
public class CommonResources {
public static Bitmap photoFinishBitmap = null;
}
in my 1st acitiviy:
Constants.photoFinishBitmap = photoFinishBitmap;
Intent intent = new Intent(mContext, ImageViewerActivity.class);
startActivity(intent);
and here is the onCreate() of my 2nd Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap photo = Constants.photoFinishBitmap;
if (photo != null) {
mViewHolder.imageViewerImage.setImageDrawable(new BitmapDrawable(getResources(), photo));
}
}

Categories

Resources