Android - how to create file object from Imageview image - android

Im making and android app which let the user select an image from the phone and load it to an ImageView. The further process is to send the image as a POST request to a PHP script
It all works fine if I load the image to a File object from the file location, but this require that the user open a setting on the phone which allow the app to access and manage local files..
So, is there a way to read the image from the imagview into a File object?
This is my current working code
val fil = File(getRealPathFromURI(imageUri!!).toString())
if (Build.VERSION.SDK_INT >= 30){
if (!Environment.isExternalStorageManager()){
var getpermission = Intent()
getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(getpermission);
}
}
var reqB = RequestBody.create("image/*".toMediaTypeOrNull(),fil)
var part = MultipartBody.Part.createFormData("file",fil.name,reqB)

Kotlin throws an access error if I try to load it to a File object if the users dont allow it through the settings on the phone. I believe its a security issue on android.
Really what I want to do is
Let the user select an existing image on the phone
Display it in an imageview
Create a function which get the selected image into an MultipartBody.part without the user having to grant the app access to special rights

Related

Firebase photoURL is not displaying properly in react-native

I'm using the Firebase authentication module in react-native with native-cli. On sign up, I'm uploading an image using react-native-document-picker. After selecting an image from the gallery it will look like this:
{
"fileCopyUri":"content://com.android.providers.media.documents/document/image%3A33077",
"name":"IMG-20211005-WA0007.jpg",
"size":67094,
"type":"image/jpeg",
"uri":"content://com.android.providers.media.documents/document/image%3A33077"
}
and using this function to upload it on firebase:
auth().currentUser.updateProfile({
displayName:fullname,
photoURL:JSON.stringify(pic),
})
now when I get it like this:
const fireUser = auth().currentUser;
console.log(JSON.parse(fireUser.photoURL))
It displays the image on the screen but when I quit the app and again open or log in to the app it's not displaying the image but I'm having pic in photoURL.
Is it possible to convert file?
{
"fileCopyUri":"content://com.android.providers.media.documents/document/image%3A33077",
"name":"IMG-20211005-WA0007.jpg",
"size":67094,
"type":"image/jpeg",
"uri":"content://com.android.providers.media.documents/document/image%3A33077"
}
into URL?
What am I doing wrong?
The URL you're passing to updateProfile is a local URL on your Android device, which won't work. To ensure the profile is visible, upload the local file to a public place in the cloud, and then pass the URL for that location to updateProfile.
For example, you can upload the file to Cloud Storage with Firebase, then get the download URL that provides read-only, public access to it, and store that in the user profile.

Path to Local Image Specified in JSON

I'm working with a tutorial fromRay Wenderlich (https://www.raywenderlich.com/124438/android-listview-tutorial). In the tutorial, an image is retrieved via the Internet using a URL specified in the locally stored JSON file:
"image" : "https://www.edamam.com/web-img/341/3417c234dadb687c0d3a45345e86bff4.jpg"
The string is stored in the imageUrl variable:
recipe.imageUrl = recipes.getJSONObject(i).getString("image");
Then the image is loaded using Picasso:
Picasso.with(mContext).load(recipe.imageUrl).placeholder(R.mipmap
.ic_launcher).into(thumbnailImageView);
I would like to change the code in the tutorial so that the image is retrieved from the drawable folder within the app, rather than via the Internet. I've been working on this on and off for several days. I assumed it was a matter of changing the URL in the JSON data so that it specified a path to the image file in the drawable folder like this:
"image" : "android.resource://com.raywenderlich.alltherecipes/drawable/chicken.jpg"
So far I've been unsuccessful. Am I on the right path, or am I way off? I'm an Android newbie. I'm used to working with plists in Xcode (although I'm no expert there, either).

Save pdf without showing the user the print dialogue screen

I'm using Xamarin.android and I followed this
I Want to save a print to a specific path without showing dialogue screen to user.
How can I say the path I want to save without asking user ?
I have that code:
myWebView = new Android.Webkit.WebView(this.Context);
var printManager = (Android.Print.PrintManager)Forms.Context.GetSystemService(Android.Content.Context.PrintService);
var text = new ContractHTML() { Model = new Model.Model() { img = null } };
myWebView.LoadDataWithBaseURL("file:///android_asset/", text.GenerateString(), "text/html", "UTF-8", null);
string fileName = "MyPrint_" + Guid.NewGuid().ToString() + ".pdf";
var printAdapter = myWebView.CreatePrintDocumentAdapter(fileName);
Android.Print.PrintJob printJob = printManager.Print("MyPrintJob", printAdapter, null);
This code is working and generate a pdf, but it's asking user where to save it, I want to save it in some path.
Is it possible ?
Save pdf without showing the user the print dialogue screen
AFAIK you can not implement this feature in Android.
The user needs to be able to choose some configuration, such as choosing what printer to print on. So when you use printManager.Print() method a print dialog will show up. You could find that In android PrintManager Source code, PrintManager class is final(In C# it's sealed), we are not allowed to override this method to prevent the dialog.
When you execute printManager.Print("MyPrintJob", printAdapter, null) method from an Activity, it starts PrintJob also it will bringing up the system print UI. This is did by Android printing framework, we cannot silently print by using the platform API.
There is an open issue on AOSP issue tracker : https://code.google.com/p/android/issues/detail?id=160908.
After searching far and wide, I used this GitHub project to solve this problem. I was able to silently print the document without the user's knowledge.
It seems like the developer was able to add some classes to the android.print package to access private members, making this possible.
https://github.com/UttamPanchasara/PDF-Generator?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=7355

Upload photo from Android device to Django backend and save it to database

I have to upload an image from Android device to a web app written in Python and Django. For storing images, I have made use of easy thumbnails.
What I have done so far is convert the image to base64 string to and post it to server. Well this is working perfectly, also if I write the base64 string to png image file it goes smoothly.
Now, I want to save it to the database as far as I know, easy thumbnails save the actual file to some location on server within the app file structure, and saves a link to same in database.
I am not understanding, how do I save the base64 string I receive in POST to my database.
My Model:
class Register(models.Model):
image = ThumbnailerImageField(upload_to=filename, blank=True, null=True, max_length=2048)
def filename(inst, fname):
f = sha256(fname + str(datetime.now())).hexdigest()
return '/'.join([inst.__class__.__name__, f])
The image is not stored in the db. It is stored to disk. Only a reference to the file is stored in the db.
def Article(models.model):
image = models.ImageField(...)
Somewhere you create a new object:
from django.core.files.base import ContentFile
obj = Article()
data = base64.b64decode(encoded)
# You might want to sanitise `data` here...
# Maybe check if PIL can read the `data`?
obj.image.save('some_file_name.ext', ContentFile(data))
obj.save()

URL Error posting image to facebook

I want to send a image taken by the user to a Facebook share dialog post.
The image taken from device camera h is set to a imageview and also saved to the device external storage/ SD card.
The facebook share SDK takes a URL for a image in the .setPicture(URL) method.
So my question is it possible to get the URL of a image from either the bitmap in the imageview or the image stored in the deice?
Or is the URL specifically for a network resource?
Cheers
ciaran
EDIT: Have tried adding the path to sd card/external storage of device as a string to the
setLink(URL string) method:
setLink("/storage/emulated/0/dive_photos/image2462.png")
but image does not load, exceptions thrown in Logcat is ....
03-02 00:06:04.280: E/Activity(3055): Error:
com.facebook.FacebookException: Error publishing message Share preview
could not be fetched
(#100)picture url not properly formed
Treied removing the first "/" by getting substring(1) and passing setLink("storage/emulated/0/dive_photos/image2462.png")
but same error....
Although a network resource url works fine:
setLink("http://www.mooneycallans.com/images/Gallery/image51.jpg")
EDIT:
Also tried creating a file://imagePathString URL some progress made, the share preview will show the image however will still not post get the same (#100) Pictire URL not properly formed....
File imagePathFile = new File(savedImagePath);
try{
userImageURL = imagePathFile.toURI().toURL();
Log.d(TAG, "File URL for saved image on FB: " + userImageURL);
}catch(MalformedURLException ex){
//ex.printStackTrace();
}
userImageURLString = userImageURL.toString();
setPicture(userImageURLString)
//userImageURLString = "file:/storage/emulated/0/dive_photos/image4373.png";
My head is wrecked:(
After much seraching a very confusing FB documentation I found the method
setPicture(URL string)
will only accept a network resource URL.
To upload a photo form app need the Request class:
Request.newUploadPhotoRequest(session, imagePathFile, uploadPhotoRequestCallback);

Categories

Resources