I have a simple module of working with the camera. When I use the default camera (in-built camera) it is displaying the thumbnail as required. Anyhow when I use 3rd party camera apps(like candycamera, retrica etc) by using packageManager to take a picture, it doesn't show the thumbnail. it crashes sometimes.
I have tried every code within my limits to check that the thumbnail is being displayed but cannot find any relevant solution
Help is appreciated
Thanks
in onCreate()
private void dispatchPicIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE );
}
}
in onActivityResult()
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss").format(new Date());
pictureFile = new File(Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp);
try {
FileOutputStream fos = new FileOutputStream(
pictureFile);
Bundle extras = data.getExtras();
Bitmap bm = (Bitmap) extras.get("data");
bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
filePath = pictureFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use CWAC2 library https://github.com/commonsguy/cwac-cam2 to take a picture. Really useful and easy to understand library.
you can use https://github.com/jkwiecien/EasyImage library to take a picture.its easy to understand.
Related
In my android app, I use the Camera intent to click a photo and upload the same to my server for processing. However, there is a requirement that the resolution of the image should be more than 500X500.
The default camera resolution is much higher these days and hence the desired resolution is not an issue. However, in most cases the resolution is much higher and the image size comes up to 3 MB or so. Because of this, it takes longer to upload the image to server, especially in areas where internet connectivity is poor.
I would like to reduce the size of the image, preferably down to 100 KB or so, without reducing the resolution.
My code for capturing the image through intent is:
imageHolder = (ImageView)findViewById(R.id.cPhoto78);
imageHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File outputFile1 = new File(getExternalStorageDirectory(), "/APDCLSBM/APDCL1.jpg");
outputFile1.delete();// Deletes the existing photo
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Toast.makeText(getBaseContext(),"Error in clicking picture",
Toast.LENGTH_SHORT).show();
finish();
}
Intent a = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (photoFile != null) {
Uri outputFileUri = FileProvider.getUriForFile(photoCamera.this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
a.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(a, 1);
}
}
});
The following function creates the image file and path:
private File createImageFile() throws IOException {
String imageFileName = "APDCL1";
File storageDir = new File(
getExternalStorageDirectory() + IMAGE_DIRECTORY);
File image = new File(storageDir, imageFileName+".jpg");
currentPhotoPath = image.getAbsolutePath();
Log.d("path1",currentPhotoPath);
return image;
}
Please suggest a way
private File createImageFile() throws IOException {
String imageFileName = "APDCL1";
File storageDir = new File(
getExternalStorageDirectory() + IMAGE_DIRECTORY);
File image = new File(storageDir, imageFileName+".jpg");
try{
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath);
}catch(Exception e){ e.printStacktrace(); return null;}
File reducedSizeImage = new File.createTempFile("name",".jpg",location);
try ( FileOutputStream outputStream = new FileOutputStream(reducedSizeImage))
{
image.compress(Bitmap.CompressFormat.JPEG,20, outputStream); // this line will reduce the size , try changing the second argument to adjust to correct size , it ranges 0-100
} catch (Exception e) {
e.printStackTrace();
return null;
}
return reducedSizeImage // otherwise upload this file
}
Have a good day
I have problem with my android code for taking screenshot while on video calling
I found several method for take screenshot on specific layout and this is what I used :
private void takeScreenshot() {
final FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container);
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
container.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(container.getDrawingCache());
container.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
if(mPath!=null){
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
}
else{
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);
unsavedToast.show();
}
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
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);
}
i try this code for save my draw painting application that will save the drawing layout and then i try to use the same method for save video call layout but return black screen image.
i found that this method cannot use for real-time when i want to record it in video
source : How to programmatically take a screenshot in Android?
so, anyone help me what the best way to solve my problem ?
When I try to share an screenshot via the Samsung email app the preview of the image I am sending is wrong. It happens only with the Samsung email app.
Here is my code:
-------here I am taking a screenshot-----------
String mPath = "";
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + "share" + ".jpeg";
// create bitmap screen capture
View v1 = getActivity().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();
-------sending a screen shot via intent-----------
Uri imageUri = Uri.parse(sorcUrl);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent, "Share"));
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
I use below code to take screen shot from my layout and share it via android intent but the captured screen shot in the selected app is not showing any thing.
#Override
public void onClick(View view) {
shareBitmap(this,takeScreenshot());
}
public Bitmap takeScreenshot() {
try{
View rootView = getWindow().getDecorView().findViewById(R.id.lyt_main_report_activity);
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}catch (Exception ex){
ex.printStackTrace();
}
return null;
}
public static void shareBitmap(Context context, Bitmap bitmap){
//save to sd card
try {
File cachePath = new File(context.getCacheDir(), "images");
cachePath.mkdirs(); // don't forget to make the directory
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); // overwrites this image every time
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
//start share activity
File imagePath = new File(context.getCacheDir(), "images");
File newFile = new File(imagePath, "image.png");
Uri contentUri = Uri.fromFile(newFile); //FileProvider.getUriForFile(context, "com.persianswitch.apmb.app.fileprovider", newFile);
if (contentUri != null) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
//shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
// shareIntent.setDataAndType(contentUri, context. getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.setType("image/*");
context.startActivity(Intent.createChooser(shareIntent, context.getResources().getString(R.string.share_using)));
}
}catch (Exception ex){
ex.printStackTrace();
}
}
Please use this code this is tested code :
public static void takeScreenshot(Context context, View view) {
String path = Environment.getExternalStorageDirectory().toString() +
"/" + "test.png";
View v = view.findViewById(android.R.id.content).getRootView();
v.setDrawingCacheEnabled(true);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
OutputStream out = null;
File imageFile = new File(path);
try {
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
} catch (FileNotFoundException e) {
// manage exception
} catch (IOException e) {
// manage exception
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception exc) {}
}
// onPauseVideo();
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
share.setType("image/png");
((Activity) context).startActivityForResult(
Intent.createChooser(share, "Share Drawing"), 111);
}
Since DrawingCache() deprecated above 28 so using Canvas will sort the issues for many. below answer can be used for share Screenshot including text without requesting for permissions.
To take the Screenshot
private Bitmap takeScreenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
To share the Screenshot
private void shareContent(Bitmap bitmap) {
String bitmapPath = MediaStore.Images.Media.insertImage(
binding.getRoot().getContext().getContentResolver(), bitmap, "title", "");
Uri uri = Uri.parse(bitmapPath);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "App");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Currently a new version of KiKi app is available.");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
binding.getRoot().getContext().startActivity(Intent.createChooser(shareIntent, "Share"));
}
if nothing happens it means your Bitmap is null kindly check that. or you could also fall on View.buildDrawingCache(); which will draw the View to Bitmap and then call your View.getDrawingCache();
also When hardware acceleration is turned on, enabling the drawing cache has no effect on rendering because the system uses a different mechanism for acceleration which ignores the flag. If you want to use a Bitmap for the view, even when hardware acceleration is enabled, see setLayerType(int, android.graphics.Paint) for information on how to enable software and hardware layers.
the quote was taken from the documented page
hope it helps
Tipp:The checked answer works when your device has external storage. On the Samsung 6 for example, it doesnt. Therefore you need to work with fileprovider.
Just incase somebody fell into this trap like me. The problem is that you are putting the name of the image twice.
FileOutputStream stream = new FileOutputStream(cachePath + "/image.png");
and than again.
File newFile = new File(imagePath, "image.png");
Change The seconed one to
File newFile = new File(imagePath);
Otherwise the contentUri give you the bitmap of your screenshot. I hope this helps someone. Took me 3 hours to figure it out :)
This question already has answers here:
Deleting a gallery image after camera intent photo taken
(13 answers)
Closed 9 years ago.
I am working on a project where I need to save images and videos in application internal memory only (not in SDCard or device Gallery). I am using below code. But this also save the image/video to device gallery. Please advice.
Bitmap bm;
View v=imageview;
v.setDrawingCacheEnabled(true);
bm=Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
String fileName="image.png";
try
{
FileOutputStream fOut=openFileOutput(fileName, MODE_PRIVATE);
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
}
catch (Exception e)
{
e.printStackTrace();
}
I want to make the image and video private and secured. So I want to save them in apps internal memory. So no other app can access it. Please suggest.
Storing the images in internal memory, it will store the image on internal images folder.
Uri uriSavedImage;
// the temp folder to start the camera activity with
String fileName = "image_" + String.valueOf(imageNum)+ ".png";
path = getDir("images", Context.MODE_WORLD_WRITEABLE).getPath() + "/" + fileName;
// start the camera activity
file = new File(path);
while (file.exists()) {
imageNum++;
fileName = "image_" + String.valueOf(imageNum)+ ".png";
path = getDir("images_pho",Context.MODE_WORLD_WRITEABLE).getPath()+ "/" + fileName;
file = new File(path);
}
Uri ur = Uri.parse(file.toString());
uriSavedImage = Uri.fromFile(file);
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hope its helps
As I told you, you can store the picture taken from the camera in the internal storage and immediately you can delete the taken image from the gallery with getContentResolver().delete(uri, null, null); or you can use this :
if (takenpicturefile.exists())
if (takenpicturefile.delete())
Log.d("tag","filedeleted");
Fore more details, you might need to refer this. Hope it helps.