Android sending email with attachment - java

I was having some problem when trying to attach a generated QR code as attachment using email in Android Programming. Here is the part where I generate the QR code and then call the send email:
#SuppressLint("NewApi")
private void generateQR() {
// Find screen size
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
// Encode with a QR Code image
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrInputText, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(),
smallerDimension);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
ImageView myImage = (ImageView) findViewById(R.id.ivImage);
myImage.setImageBitmap(bitmap);
new SendEmailAsyncTask().execute(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
class SendEmailAsyncTask extends AsyncTask <Bitmap, Void, Boolean> {
#Override
protected Boolean doInBackground(Bitmap... params) {
GMailSender sender = new GMailSender("something#gmail.com","pwd");
try {
sender.sendMail("Successful Event Registration QR Code",params[0], "something#gmail.com", "something#gmail.com");
System.out.println("send");
} catch (Exception e) {
System.err.println("err"+e);
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}
However, I am getting error message at the sendMail that line:
The method sendMail(String, String, String, String) in the type GMailSender is not applicable for the arguments (String, Bitmap, String, String)
Because previously when I replace the params[0], it was a string before that. But then I have to pass in the generated QR code bitmap into the email content. Any ideas?
Thanks in advance.
Update
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
ImageView myImage = (ImageView) findViewById(R.id.ivImage);
myImage.setImageBitmap(bitmap);
counterQR++;
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "eNeighbourhood"+counterQR+".jpg");
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = getImageBitmap(bitmap); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
With these code above, I am trying to convert bitmap into file so that I can modify the sendMail() by taking in file parameter as well. However, I am getting getImageBitmap is undefined for MainActivity

Related

How to add EditText/TextView to Android photo?

What I want to do:
When user takes a picture, I want to add custom text at the bottom of this picture
What I've tried:
I assume that I have to do 4 things in order for this to work
1. Create bitmap background eg. photo thas has been taken
private Bitmap createBitmapFromJpg(Uri mPhotoUri) throws FileNotFoundException {
File f = new File(mPhotoUri.getPath());
return BitmapFactory.decodeStream(new FileInputStream(f));
}
2. Create foreground to put on the background
Here I have error that says java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.widget.EditText.getDrawingCache()' on a null object reference
private Bitmap createBitmapToDrawOnPicture(Context context) {
LinearLayout linearLayout = new LinearLayout(context);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.setOrientation(LinearLayout.VERTICAL);
layoutParams.setMargins(2, 1, 2, 1);
linearLayout.setLayoutParams(layoutParams);
EditText editText = new EditText (context);
editText.setTextSize(15);
editText.setLayoutParams(layoutParams);
linearLayout.setGravity(Gravity.CENTER);
editText.setText("testtesttesttest");
linearLayout.addView(editText);
editText.setCursorVisible(false);
editText.buildDrawingCache();
return Bitmap.createBitmap(mEditText.getDrawingCache());
}
3. Merging both Bitmaps
private Bitmap mergeBitmapsAndConvert(Bitmap foreground, Bitmap background) {
Bitmap finalBitmap = Bitmap.createBitmap(background.getWidth(), background.getHeight(), background.getConfig());
Canvas canvas = new Canvas(finalBitmap);
canvas.drawBitmap(background, new Matrix(), null);
canvas.drawBitmap(foreground, new Matrix(),null);
return finalBitmap;
}
4. Convert from bitmap to jpg
private void convertToJpeg(Bitmap bitmap, Uri path) {
File file = new File(path.getPath());
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

How Can I Capture Multiple Images and send the images to next Activity and display them using CameraX [Android Studio]

Am using the latest cameraX
def camerax_version = "1.0.0-beta11"
I able to take picture and save image to External Storage in a folder using this below code
File photoFile = new File(outputDirectory, "Image_" + System.currentTimeMillis() + ".jpg");
ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(photoFile).build();
imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(getBaseContext()), new ImageCapture.OnImageSavedCallback() {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
Uri.fromFile(photoFile);
Toast.makeText(getBaseContext(), "Image Saved" + photoFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
Toast.makeText(getBaseContext(), "Error Saving Image" + photoFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
});
Now the point is on how to extract the image before saving it to external storage. What I want to achieve is to capture multiple images and save it in buffer and send those images to next Activity and display them in a imageView using list or something.
Now this can be achieved using onImageCapturedCallback on imageCapture which gives me a ImageProxy which then have to convert to Byte Array. But this process apples to only small size and single image.
How can I achieve this for higher resolution and multiple images.
Below is the code I used to capture ImageProxy and set imageCapture to "YUV", Sadly it didn't work at all
imageCapture.takePicture(ContextCompat.getMainExecutor(getBaseContext()), new ImageCapture.OnImageCapturedCallback() {
#Override
public void onCaptureSuccess(#NonNull ImageProxy image) {
super.onCaptureSuccess(image);
#SuppressLint("UnsafeExperimentalUsageError") Image cimage = image.getImage();
Image.Plane[] planes = cimage.getPlanes();
ByteBuffer yBuffer = planes[0].getBuffer();
ByteBuffer uBuffer = planes[1].getBuffer();
ByteBuffer vBuffer = planes[2].getBuffer();
int ySize = yBuffer.remaining();
int uSize = uBuffer.remaining();
int vSize = vBuffer.remaining();
byte[] nv21 = new byte[ySize + uSize + vSize];
yBuffer.get(nv21,0,ySize);
vBuffer.get(nv21,ySize,vSize);
uBuffer.get(nv21,ySize + vSize,uSize);
YuvImage yuvImage = new YuvImage(nv21,ImageFormat.NV21,cimage.getWidth(),cimage.getHeight(),null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0,0,yuvImage.getWidth(),yuvImage.getHeight()),100,out);
byte[] imageBytes = out.toByteArray();
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("image",imageBytes);
MainActivity.this.startActivity(intent);
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
super.onError(exception);
}
});
Can I add Image to ArrayList and then sent them over?
Thanks in Advance..
There are two ways that I did for my project. The code is in kotlin language.
You can understand it easily.
val image = imageProxy.image
val bitmap = Bitmap.createBitmap(image.width, image.height,
Bitmap.Config.ARGB_8888)
If it didn't work you can use a YuvtoRgbConvertor I have the full kotlin code if you want or you can write your own. then you can convert the bitmap like this.
val convertor = YuvToRgbConvertor
convertor.yuvToRgb(image , bitmap)
That is what I have done for my project.
What I suggest you is to store in an array list. and then pass an array list to other activities.
What you have to do is create an array list and store uri.tostring in the array list
String newurl=uri.toString
`arraylist.add(newurl)`
This way you can add multiple image URLs in ArrayList and display with the help of the Picasso library. No need to fetch images from the database.
The easiest way that I found was this
preview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap scaledBitmap = null;
ContextWrapper cw = new ContextWrapper(getApplicationContext());
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH + "myImage.jpeg");
if (file.exists()) {
myImage.setImageDrawable(Drawable.createFromPath(file.toString()));
}
else {
myImage.setImageDrawable(Drawable.createFromPath(null));
Toast.makeText(nextPage.this, "Not found", Toast.LENGTH_LONG).show();
}
}
});
You can change the path according to your code.
First you need to close the image after capturing inside the takepicture callback image.close() will close the current image . the create ArrayList globaly and add the imageURL in the arraylist . After theat you can send the arraylist to any activity by intent.
imageCapture.takePicture(ContextCompat.getMainExecutor(getBaseContext()), new ImageCapture.OnImageCapturedCallback() {
#Override
public void onCaptureSuccess(#NonNull ImageProxy image) {
super.onCaptureSuccess(image);
#SuppressLint("UnsafeExperimentalUsageError") Image cimage = image.getImage();
Image.Plane[] planes = cimage.getPlanes();
ByteBuffer yBuffer = planes[0].getBuffer();
ByteBuffer uBuffer = planes[1].getBuffer();
ByteBuffer vBuffer = planes[2].getBuffer();
int ySize = yBuffer.remaining();
int uSize = uBuffer.remaining();
int vSize = vBuffer.remaining();
byte[] nv21 = new byte[ySize + uSize + vSize];
yBuffer.get(nv21,0,ySize);
vBuffer.get(nv21,ySize,vSize);
uBuffer.get(nv21,ySize + vSize,uSize);
YuvImage yuvImage = new YuvImage(nv21,ImageFormat.NV21,cimage.getWidth(),cimage.getHeight(),null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0,0,yuvImage.getWidth(),yuvImage.getHeight()),100,out);
byte[] imageBytes = out.toByteArray();
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("image",imageBytes);
MainActivity.this.startActivity(intent);
image.close();
}
#Override
public void onError(#NonNull ImageCaptureException exception) {
super.onError(exception);
}
});
I think this will help you, any doubts just refer here to my blog post
This is the function for converting the ImageProxy to bitmap
// output of the image capture image proxy to bitmap
public Bitmap imageProxyToBitmap(ImageProxy image) {
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
buffer.rewind();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
byte[] clonedBytes = bytes.clone();
return BitmapFactory.decodeByteArray(clonedBytes, 0, clonedBytes.length);
}
And save the bitmap to your local storage
// used for save the files internal storage , can view in the gallery or internal storage
public String saveTOInternamMemory(Activity activity, Bitmap bitmapImage){
File myPath = getInternalStorageDir(internalStorageDir,imageFormat,Environment.DIRECTORY_PICTURES);
Log.d(TAG, "directory: " + myPath.getAbsolutePath());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.d(TAG, "bit exception: Success" );
} catch (Exception e) {
Log.d(TAG, "bit exception: " + e.getMessage());
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "io exce: " + e.getMessage());
}
}
Log.d(TAG, "absolute path " + myPath.getAbsolutePath());
return myPath.getAbsolutePath();
}

I'm not getting the image from the url using Glide

here is the code which I tried.
I'm not getting the image in bmp using Glide and when I pass the null bmp in the method which converts the image to the byte[] then the error occurs.
new AsyncTask() {
#Override
protected byte[] doInBackground(Void... voids) {
Looper.prepare();
byte[] byteimage = new byte[0];
Bitmap bmp1;
try {
bmp= Glide.with(specificrecipe.this)//bmp is global
.load(url2img)
.asBitmap()
.into(100,100)
.get();
byteimage=getBytes(bmp);//here I'm not getting the image in bmp
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.PNG, 0, stream);//null object refrence -> bmp
//byteimage=stream.toByteArray();
//byteimage1.add(0,byteimage);
// initialize(bmp);
}catch (final ExecutionException e){e.printStackTrace();}
catch (final InterruptedException e){e.printStackTrace();}
return byteimage;
}
//#Override
//protected void onPostExecute(byte[] Bytearray){
//byteimage1=Bytearray;
//}
}.execute();
Hope this works for you
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
//this is the way through which I get the image from URL even the glide is not working for saving the image from URL.
try {
URL url = new URL(url2img);//url2img is a String
bmp =BitmapFactory.decodeStream(url.openConnection().getInputStream());
//bmp is global variable
}catch (IOException e)
{e.printStackTrace();}
byteimage1=getBytes(bmp);

Android how to capture shadow in screenshots

How to capture shadow or elevation of views in the layout of the activity in a screenshots.This code take a screenshot for the view but it's not showing the shadow of the viewsenter image description here
View screenView = parentMain;
screenView.buildDrawingCache();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getWidth() , screenView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
screenView.layout(0, 0, screenView.getLayoutParams().width, screenView.getLayoutParams().height);
screenView.draw(c);
screenView.setDrawingCacheEnabled(false);
fakeImgView.setImageBitmap(bitmap);
Even if we add the harware acceleration at activity level it does not provides any effect.
Appreciate any alternative approaches
the result
Try this.
CardView card = (CardView) findViewById(R.id.card);
Now just pass the card to captureScreenShot(). It returns the bitmap and save that bitmap saveImage().
You can pass any view Like RelativeLayout, LinearLayout etc any view can pass to captureScreenShot().
// Function which capture Screenshot
public Bitmap captureScreenShot(View view) {
/*
* Creating a Bitmap of view with ARGB_4444.
* */
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(bitmap);
Drawable backgroundDrawable = view.getBackground();
if (backgroundDrawable != null) {
backgroundDrawable.draw(canvas);
} else {
canvas.drawColor(Color.parseColor("#80000000"));
}
view.draw(canvas);
return bitmap;
}
// Function which Save image.
private void saveImage(Bitmap bitmap) {
File file = // Your Storage directory name + your filename
if (file == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Finally call this function like this.
saveImage(captureScreenShot(card));
Now set Your Image like this.
File file = new File(“yourImageFilePath”);
if(file.exists())
{
yourImageView.setImageURI(Uri.fromFile(file));
}
Note : If setImageURI() not working then you can use below code.
File file = new File(“yourImageFilePath”);
if(file.exists())
{
Bitmap bitmap = BitmapFactory.decodeFile(file.toString());
yourImageView.setImageBitmap(bitmap);
}

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();}

Categories

Resources