Create bitmap from file return null picture - java

I wanted to do an app for sharing pictures from the gallery for learning and i want the picture to be renamed so i use a bitmap that retrieve the data of the picture. But the thing is the file is always returning null.
I have a code and i don't know where is the problem.
File file = new File(this.getFilesDir().getAbsolutePath(), "logo");
if (!file.exists()) {
file.mkdirs();
}
File iconf = new File(file, "icon_launcher.png");
iconf.createNewFile();
OutputStream ios = new FileOutputStream(iconf);
example.compress(Bitmap.CompressFormat.PNG, 80, ios);
ios.flush();
ios.close();
//String uricon= MediaStore.Images.Media.insertImage(getContentResolver(),iconf.getAbsolutePath(),"icon_launcher.png","drawing");
Uri iconurl = Uri.parse(iconf.getAbsolutePath());
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("image/png");
email.putExtra(Intent.EXTRA_STREAM, iconurl);
startActivityForResult(Intent.createChooser(email, "Envoyer par mail"), 1);
Thank you in advance for the help :)

I have succeeded to make the code work, i forget to use a FileProvider because i didn't have an External Storage.So you have to use a FileProvider to use Internal Storage.

Related

how to send a file with a picture from the app to e-mail or whatsapp (25.10.2021)

I have tried about 10 answers to a similar question, but none of them were successful. Something might be out of date. Please give an answer for today.
Simple task:
I want my app to be able to send a file with an image to e-mail or whatsapp.
I put the file with the image in the application resources in the folder Drawable.
Its size is 5 MB.
How to do this in Java?
I'm asking for code, not links to similar answers. I've tried most of them already.
Some decisions came to null.bin.
Some don't send anything at all and throw an error.
Perhaps I am not specifying any permissions.
Something else is possible.
I'm new.
I would like an answer with comments (what I am writing and why)
// step 1. I put the picture in the folder Drawable
// clicking on the button sends the picture through the messenger to other users
public void onClick_sendMyImage(View v) {
// Step 2.Convert PICTURE to Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
saveImage(bitmap); // 3. save the PICTURE in the internal folder
send(); // 4.sending PICTURE (function code below)
}
// step 3. Saving the image in the internal folder:
private static void saveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
//Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "image_test" + ".jpg";
File file = new File(myDir, fname);
if(file.exists()) file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Step 4. Sending the saved PICTURE
public void send(){
try{
File myFile = new File("/storage/emulated/0/saved_images/image_test.jpg");
// for something I create this type (so it is said in one of the answers)
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(type);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(myFile));
Intent intent1 = Intent.createChooser(intent, "what do you want to send ?");
startActivity(intent1);
}catch (Exception e){
Toast.makeText(this, "repeat sending", Toast.LENGTH_SHORT).show();
}
}
Sending an image from an app turned out to be not a good idea.
The image cannot be edited if necessary.
Over time, you may want to add more images, etc..
I did it differently, and it turned out better:
I put the image on GoogleDisk.(now I can change it at any time without having
to ask users to reinstall the application every time the picture changes).
I placed a link to the picture in the FireBase Database. (I also placed a banner with a picture here.).
I connected the application to the Firebase Database.
In the activity I made a RecyclingView, where I get a banner(s) and a link(s) to the original image(s). The user can download this link or send it through whatsapp anywhere and download the original picture in good quality (A1, 2.5Mb).
thanks, guys..
I thank the guys for the tips, especially mr.Blackapps. In this case, you really can't do without a FileProvider.

File Couldn't Save On All real device Android Studio

//Save PDF file
//Create time stamp
Date date = new Date() ;
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss").format(date);
String filePath = Environment.getExternalStorageDirectory() +"/"+ "Allotment" +timeStamp+ ".pdf";
File myFile = new File(filePath);
try {
OutputStream output = new FileOutputStream(myFile);
pdfDocument.writeTo(output);
output.flush();
output.close();
Toast.makeText(AllotmentDoc.this, "PDF Created Succesfully", Toast.LENGTH_LONG).show();
Toast.makeText(AllotmentDoc.this, "PDF Saved On Memory", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
I want to save my pdf file that's why I wrote some line of code. But it works on some device and doesnt work on some other device. What is the problem. how can i solve it.
I think you are facing this problem in some deviece because of
Environment.getExternalStorageDirectory()
You can use
Environment.getExternalStorageDirectory().getAbsolutePath();
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. Galaxy Tab 2, Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time.

Unable to attach picture programmatically in email

I have a function that I want to automatically take a screenshot and then upload it to the users preferred email app.
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 + ".png";
// 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.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + now + mPath);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"Enter your email address"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Journey : ");
startActivity(Intent.createChooser(emailIntent , "Select your preferred email app.."));
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
This is my function. It is taking the screen shot automatically and its store it on my local device. It is also prompting the user to select their email app. Then I select an app it says "unable to attach file" . I have read and write permissions in my manifest.
The other app may not have access to external storage. Plus, your code will crash on Android 7.0+, once you raise your targetSdkVersion to 24 or higher.
Switch to using FileProvider and its getUriForFile() method, instead of using Uri.fromFile().
And, eventually, move that disk I/O to a background thread.
check this link -
https://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html
and How to send an email with a file attachment in Android
Hope this help.
The problem was :
Uri path = Uri.fromFile(filelocation);
Instead I used :
File filelocation = new File(MediaStore.Images.Media.DATA + mPath);
Uri myUri = Uri.parse("file://" + filelocation);
Hopefully this helps anyone facing the same problem.

Android - Copy image to clipboard, anyone got this working?

I am trying to copy a image file from my apk to the clipboard.
Here is how I am approaching it (roughly, i'm using a content provider locally which is out of the scope of the question.
ClipboardManager mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "Image/jpg");
values.put(MediaStore.Images.Media.DATA, filename.getAbsolutePath());
ContentResolver theContent = getContentResolver();
Uri imageUri = theContent.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
ClipData theClip = ClipData.newUri(getContentResolver(), "Image", imageUri);
mClipboard.setPrimaryClip(theClip);
With this code two things can happen:
1) java.lang.IllegalStateException: Unable to create new file
2) When pasting it only pastes the URI itself, not the image (even in compatible apps)
I don't see any example of anyone getting image pasting on android working, and I have searched for an answer extensively, both on google and stack overflow.
Can anyone help with this?
I would really appreciate someones assistance here.
PS: If it's just not possible to do I would also like to know that, to save wasting anymore time on this.
Thanks!
I have an option. Use the app SwiftKey as your keyboard on Android (it worked on Android 10). It allow you to access your photos library, so you will need to 1) download the image 2) open whatever app you are using and want to paste the image 3) using your SwiftKey keyboard, click on the "+" signal and then on the "pin" symbol (should be in the first line). 4) Finally, click on "create new" and it will access your photos to insert IN-LINE ANYWHERE.
I know that's not the best solution while on iOS you can just tap copy and paste. But it was the only solution that worked for me. Try for yourself. I hope that helps :)
There is no indication that such functionality is supported in Android.
The behavior is correct and the uri is the copied data not the bitmap.
It depends on whether the place you are pasting in can handle this uri.
The issue to the OP is this
values.put(MediaStore.Images.Media.MIME_TYPE, "Image/jpg");
This is an invalid mime type. It should be
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
you can not copy that to clipboard because its impossible;
but you can do that by copying that to sdcard and then access that from every where that you want;
here is some code that helped me a lot and can help you too:
Context Context = getApplicationContext();
String DestinationFile = "the place that you want copy image there like sdcard/...";
if (!new File(DestinationFile).exists()) {
try {
CopyFromAssetsToStorage(Context, "the pictures name in assets folder of your project", DestinationFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
InputStream IS = Context.getAssets().open(SourceFile);
OutputStream OS = new FileOutputStream(DestinationFile);
CopyStream(IS, OS);
OS.flush();
OS.close();
IS.close();
}
private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
byte[] buffer = new byte[5120];
int length = Input.read(buffer);
while (length > 0) {
Output.write(buffer, 0, length);
length = Input.read(buffer);
}
}

Delete a File given an url using java

URL urlImage = new URL(candidateImagePath);
BufferedImage image = ImageIO.read(urlImage);
String imageName = urlImage.getFile().split("/")[3];
String pathImage = messageSource.getMessage("consultant.image", null, Locale.ENGLISH)+messageSource.getMessage("system.slash", null, Locale.ENGLISH)+candidateid;
File fileDir = new File(pathImage);
fileDir.mkdirs();
ImageIO.write(image, "jpg" ,new File(pathImage+messageSource.getMessage("system.slash", null, Locale.ENGLISH)+imageName));
I am trying to get an image uploaded by iphone guys to a temporary url .
I read the image and write it to my desired location which is 'pathImage'.
Till here everything works fine.
I want to delete the temporary file in the url.
I want to know how can I delete the image when the url is given in java. Kindly help on this .
You need to write a wrapper on target URL, which will simply delete the file passed as a query string like
http://your_temp_url/deleteimage?file=your_temp_file_name
in deleteimage you will code like this
private void deletefile(String file)
{
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
out.println("Deletion failed.");
}else{
out.println("File deleted.");
}
This is just one approach to delete the image located on remote machine.
new File(url.toURI()).delete();
should do the trick.
example:
URL url=getClass().getResource("/someresources/resourceFile.txt");
File f=new File(url.toURI());
f.delete();

Categories

Resources