how to solve getContentResolver().getType null? - android

I am trying to execute following like following
Uri.parse(pictureImagePath) is
/storage/emulated/0/Pictures/20171125_131914.jpg
But it is returning null.
Am i missing something??
Please help!!!
Following is calling the camera:
if(Build.VERSION.SDK_INT>=24){
try{
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
}catch(Exception e){
e.printStackTrace();
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, REQUEST_CAMERA);
following is the code
File imgFile = new File(pictureImagePath);
if (imgFile.exists()){
bitmapImage = null;
bitmapImage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(imgFile))), imgFile);

Related

Android Camera Image not uploading in Gallery

Here is my code for the Camera Activity that captures then store the photo.
private void cameraIntent(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, TAKE_IMAGE_CODE);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "MyApp" + timeStamp + ".jpeg";
File storageDir = Environment.getExternalStorageDirectory();
File dir = new File(storageDir.getAbsolutePath()+ "/Pictures/MyApp/");
dir.mkdir();
File image_file = new File(dir, imageFileName);
currentPhotoPath = image_file.getAbsolutePath();
return image_file;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
Log.d("galleryAddPic", contentUri.toString());
}
And I'm calling these methods by:
case R.id.photoSelection_Camera:
cameraIntent();
galleryAddPic();
break;
The photo does get saved in the folder when I took a look in the device folder.
However it takes really long time for me to see the photo from the gallery.
Anyone know what is the issue here?

How to create separate folder for captured images with losing quality

Hi i am trying to create separate folder for captured images with out losing quality using below code but i am getting exception android.os.FileUriExposedException: file:///storage/emulated/0/myFolder/photo_20180504_102426.png exposed beyond app through ClipData.Item.getUri()
what did do mi-stack can some one correct my code
code:
String folder_main = "myFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory(), "/myFolder" + "/photo_" + timeStamp + ".png");
imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, Constants.CAMERA_REQUEST_CODE);
private void onCaptureImageResult(Intent data) {
try {
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
CircleImageView circleImageView = findViewById(formFields.get(imagePosition).getId());
circleImageView.setImageBitmap(thumbnail);
}
Put This on Your oncreate()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

how to share gif images using intent sharing to available apps?

i want working on sharing .gif with available apps like whatsapp, but unable to get valid Uri of gif present in my drawable resource.
Uri path = Uri.parse("android.resource://my_package_name/" + R.drawable.gif_1);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
shareIntent.putExtra(Intent.EXTRA_STREAM, path);
there is lot of solution on sharing images but no solution on gif sharing, Please help
I found my answer, I just created a file with a .gif extension and it worked for me. See the code below:
private void shareGif(String resourceName){
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "sharingGif.gif";
File sharingGifFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));
FileOutputStream fos = new FileOutputStream(sharingGifFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}
if you want to take image from internal storage.
//this is method having internal storage path.
private String getFilePath2() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Gifs temp/");
if (!myDir.exists())
myDir.mkdirs();
String fname = "temp_gif";
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);
File file = new File(myDir, fname + "_" + filename + ".gif");
if (file.exists()) {
file.delete();
}
String str = file.getAbsolutePath();
return str;
}
// Then take image from internal storage into the string.
String st = getFilePath2();
//And share this by this intent
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM,
uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));

When I capture image from camera it lost the quality of image? What to do?

My code for clicking on an image is:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 300);
Code of Activity Result:
if (requestCode == 300) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(number.equalsIgnoreCase("1"))
{
imageViewOneNumber.setImageBitmap(thumbnail);
image1="";
image1= getEncoded64ImageStringFromBitmap(thumbnail);
}
else
{
RelativeLayoutImage2.setVisibility(View.GONE);
FrameImage2.setVisibility(View.VISIBLE);
imageViewTwoNumber.setImageBitmap(thumbnail);
image2="";
image2= getEncoded64ImageStringFromBitmap(thumbnail);
}
}
Image of camera capture demo:
Please help me solve this problem. When I click on the photo from the camera it decreases the size of the image.
From the docs
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Sample Code from there
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Implement it like that:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File image = createImage(this);
Uri uri = Uri.parse("file://" + image.getAbsolutePath());
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST);
public File createImage(Context context) throws IOException {
File dir = new File(Environment.getExternalStorageDirectory() + "/" + context.getString(R.string.company_name) + "/Images");
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new IOException("Something wrong happened at" + dir);
}
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.getDefault()).format(new Date());
String imageName = context.getString(R.string.app_name) + "_" + timeStamp + ".jpg";
return new File(dir.getPath() + File.separator + imageName);
}
And finally in onActivityResult() you can get your image:
if (requestCode == CAMERA_REQUEST) {
//Here you can load image by Uri
}
Use this code may be its helps you
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String path=Environment.getExternalStorageDirectory()+File.separator+Constants.APP_FOLDER_NAME+File.separator+Constants.ATTACHMENTS_FOLDER_NAME;
File mediapath=new File(path);
if(!mediapath.exists())
{
mediapath.mkdirs();
}
captured_image_uri=null;
captured_image_uri=Uri.fromFile(new File(mediapath.getPath(),"Image"+System.currentTimeMillis()+".jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT,captured_image_uri);
startActivityForResult(intent, Constants.PICK_FILE_FROM_CAMERA);
onActivityResult write this code
if(requestCode==Constants.PICK_FILE_FROM_CAMERA&&resultCode==getActivity().RESULT_OK)
{
try
{
if(captured_image_uri!=null) {
ExifInterface exifInterface = new ExifInterface(captured_image_uri.getPath());
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: {
matrix.postRotate(90);
break;
}
case ExifInterface.ORIENTATION_ROTATE_180: {
matrix.postRotate(180);
break;
}
case ExifInterface.ORIENTATION_ROTATE_270: {
matrix.postRotate(270);
break;
}
}
FileInputStream fis = new FileInputStream(captured_image_uri.getPath());
Bitmap bmp = BitmapFactory.decodeStream(fis);
Bitmap rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
FileOutputStream fos = new FileOutputStream(captured_image_uri.getPath());
rotated.compress(Bitmap.CompressFormat.JPEG, 85, fos);
uploadFileToServer(captured_image_uri.getPath());
}
}catch (Exception e)
{
e.printStackTrace();
}
}

Creating folder with user input : Android

jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//int imageNum = 0;
String Name = PatientInfo.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory().toString() + Name);
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
// String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
// File output = new File(imagesFolder, fileName);
/* while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}*/
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
This is a code example. I am trying to create folder with a userinput when it is entered. Each time i need to create new folders on entering new username. But in this there is something missing.Any suggestions will be helpful.
Change
File imagesFolder = new File(Environment.getExternalStorageDirectory().toString() + Name);
withFile
File imagesFolder = new File(Environment.getExternalStorageDirectory(), Name);
Please be sure to have also the WRITE_EXTERNAL_PERMISSION in the manifest, and that Name is not null

Categories

Resources