Use Floating Widget to take screenshot of any screen - java

I am trying to take a screenshot using Floating Widget. But I can't find any way of doing so. I searched for MediaProjection API but couldn't find anything helpful. Right now, If I tap the floating widget, it only captures the screenshot of the floating widget.
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Screenshot.java is my class for taking the screenshot
Bitmap bitmap = Screenshot.takescreenshotOfView(v);
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "DUOProfile" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "profilepic"+".jpg");
Toast.makeText(getApplicationContext(), "Picture saved in DUOProfile folder",Toast.LENGTH_SHORT).show();
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error occured. Please try again later.",Toast.LENGTH_SHORT).show();
}
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
}
});
Screenshot.java
package com;
import android.graphics.Bitmap;
import android.view.View;
public class Screenshot {
public static Bitmap takescreenshot(View view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public static Bitmap takescreenshotOfView(View view) {
return takescreenshot(view.getRootView());
}
}

Pass the view in takescreenshotOfView method
Bitmap bitmap = takescreenshotOfView(view);
This will return bitmap image, just saved in your internal/sd card
public Bitmap takescreenshotOfView(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}

Related

How to get images from SD-card in ImageView?

There is a function that records the image on the SD card
String folderToSave = Environment.getExternalStorageDirectory().toString();
private String SavePicture(ImageView iv, String folderToSave)
{
OutputStream fOut = null;
try {
File file = new File(folderToSave, mainText.getText()+".jpg");
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable) iv.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
}
catch (Exception e)
{
return e.getMessage();
}
return "";
}
The function code is taken from Habr
I'm trying to set an ImageView via setImageDrawable but I'm getting an error
mainText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable d = Drawable.createFromPath(folderToSave+mainText.getText()+".jpg");
ImageView.setImageDrawable(d);
}
});
Error
non-static method setImageDrawable(Drawable) cannot be referenced from a static context ImageView.setImageDrawable(Drawable.createFromPath(folderToSave+mainText.getText()+".jpg"));
Is there any other way to set the picture saved on the phone?

Taking Screenshot and Sharing - Android

Trying to Take Screenshot, and Share that image.
Tried bunch of codes, stack, youtube. dont know where is the problem in my code.
Taking screenshot as unknown format. Tried png,jpeg. still remains same.
Screen while share intent
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
View rootView = getWindow().getDecorView().getRootView();
Button bat = findViewById(R.id.btsharee);
bat.setOnClickListener(
view ->
shareImage(store(getScreenShot(rootView),"sos.jpeg")));
}
method for screenshot and storing
public static Bitmap getScreenShot(View view) {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public static File store(Bitmap bm, String fileName){
final String dirPath = Environment
.getExternalStorageDirectory().getAbsolutePath() +"/Screenshots";
File dir = new File(dirPath);
if(!dir.exists()){
boolean mkdir = dir.mkdir();
}
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG,100, fOut);
fOut.flush();
fOut.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return dir;
}
private void shareImage(File file){
Uri uri;
if (Build.VERSION.SDK_INT < 24) {
uri = Uri.fromFile(file);
uri = Uri.parse(file.getPath());
} else {
uri = Uri.parse(file.getPath());
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*"); //also tried image/jpeg
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "Msg:" );
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
}
}
I checked storage permission, but storage permission have no problem.
Can anyone help me out..?

How to share image with a button? [duplicate]

This question already has answers here:
How to use "Share image using" sharing Intent to share images in android?
(17 answers)
Closed 2 years ago.
I am making QR code generator
So far I made a generator button and save button.
It works fine.
I am trying to work on the sharing button.
It takes a few days to figure out as a beginner and still I cannot make it work.
At this code, if I click share, then the app closes.
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
I guessed the problem was path.
I use savepath to save qr code image. And then maybe it conflicts with String path
So I tried String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";;
It's not working. So maybe it's different problem and I don't know how to fix it.
Could you show me how to fix?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(view -> {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
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;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast toast= Toast.makeText(getApplicationContext(),
"Image Saved. Check your gallery.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
}
}
I think you can solve this by:
Saving the bitmap in a file.
Then sharing the URI of that file in the intent.
In the code below, I am saving the image at the app level directory, you can choose your own and the code is written in kotlin.
Note: If you are using an app-level directory for saving the image then you must use the file provide to get the URI else it may result in FileUriExposedException
try {
val file = File(getExternalFilesDir(null),System.currentTimeMillis().toString() + ".png")
file.createNewFile()
val b = imageView.drawable.toBitmap()
FileOutputStream(file).use { out ->
b.compress(Bitmap.CompressFormat.PNG, 100, out)
}
val share = Intent(Intent.ACTION_SEND)
share.type = "image/jpeg"
val photoURI = FileProvider.getUriForFile(this, applicationContext.packageName.toString() + ".provider", file)
share.putExtra(Intent.EXTRA_STREAM, photoURI)
startActivity(Intent.createChooser(share, "Share Image"))
Toast.makeText(this, "Completed!!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
In JAVA:
public void shareImage(Activity activity, ImageView imageView) {
try {
File file = new File(activity.getExternalFilesDir(null), System.currentTimeMillis() + ".png");
file.createNewFile();
Bitmap bitmap = drawableToBitmap(imageView.getDrawable());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Intent share = new Intent("android.intent.action.SEND");
share.setType("image/jpeg");
Uri photoURI = FileProvider.getUriForFile(activity,activity.getPackageName(), file);
share.putExtra("android.intent.extra.STREAM", photoURI);
activity.startActivity(Intent.createChooser(share, "Share Image"));
} catch (Exception var14) {
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}

How can I take Screenshots using Arcore?

I am trying to take a screenshot of my Augmented Reality Screen and pass it as a bitmap to another activity.
This is the code that I am using to take the screenshot:
Function to take screen shot
public static void tmpScreenshot(Bitmap bmp, Context context){
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(context, CostActivity.class);
in1.putExtra("image", filename);
context.startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
Function to receive screenshot
private void loadTmpBitmap() {
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
ImageView imageView = findViewById(R.id.test);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 120, 120, false));
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Even though the Screenshot was taken, it was black when it is passed to another activity.
In addition, the Screenshot only appeared after I pressed the back button
Can anyone help me with the code to take a screenshot with ARCore? Or what am I doing wrong?
It is not possible to take a screenshot of a SurfaceView using your method. If you do then the screenshot will be black, as it only works for regular views.
What you need to use is pixelcopy.
private void takePhoto() {
ArSceneView view = arFragment.getArSceneView();
// Create a bitmap the size of the scene view.
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
// Create a handler thread to offload the processing of the image.
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
// Make the request to copy.
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap);
} catch (IOException e) {
Toast toast = Toast.makeText(VisualizerActivity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Screenshot saved in /Pictures/Screenshots");
} else {
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Failed to take screenshot");
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
public void saveBitmapToDisk(Bitmap bitmap) throws IOException {
// String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots/";
if (videoDirectory == null) {
videoDirectory =
new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Screenshots");
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String formattedDate = df.format(c.getTime());
File mediaFile = new File(videoDirectory, "FieldVisualizer"+formattedDate+".jpeg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}

Resizing image file rotate it horizontally android

Hey I have an app that choose an image from the gallery , resizing it and uploading it to ftp server , but I have notice that in some photo's the app flips the image horizontally and upload it backwards, I can't figure out why it is happening (It only happened on some photos and on others not, usually happened on photos taken from my camera)
Here is the code for the resize part:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK&&data!=null) {
selectedImageURI = data.getData();
showUri = data.getData();
imagePath = RealPathUtil.getPath(this,data.getData());
loadedImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
//loadedImage.setImageURI(data.getData());
Glide.with(this).load(data.getData())
.into((ImageView) findViewById(R.id.upload_image1));
ImageView m =(ImageView)findViewById(R.id.remove_image);
m.setFocusable(true);
m.setVisibility(View.VISIBLE);
File file = new File(RealPathUtil.getPath(this,data.getData()));
Bitmap bitmap = decodeFile(file);
ImageResizer(bitmap);
}
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=200;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bit1 = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
//Matrix matrix = new Matrix();
//matrix.postRotate(45);
// Bitmap rotatedBitmap = Bitmap.createBitmap(bit1 , 0, 0, bit1 .getWidth(), bit1 .getHeight(), matrix, true);
return bit1;
} catch (FileNotFoundException e) {}
return null;
}
private void ImageResizer(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pic");
if(!myDir.exists()) myDir.mkdirs();
String fname = "resized.png";
File file = new File (myDir, fname);
if (file.exists()){
file.delete();
Log.d("exist","replace");
SaveResized(file, bitmap);
} else {
SaveResized(file, bitmap);
Log.d("saved","now");
}
selectedImageURI = Uri.fromFile(file);
imagePath = RealPathUtil.getPath(this,selectedImageURI);
}
private void SaveResized(File file, Bitmap bitmap) {
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
can someone help me and tell me why is it happening?

Categories

Resources