bitmap to file that can be uploaded via async - android

After a day of headaches due to previous problems implementing a working photo upload system I feel im in the home stretch. my last and final step is to allow my users to upload a image once it has been cropped.
after cropping takes place I have access to a bitmap and a imageView that is using the bitmap.The async request lib im using is : http://loopj.com/android-async-http/
and the api im using is setup in such a way that i need to send over a "file" like so:
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
What are my options for turning my bitmap into a "file"

You can save Bitmap to file using Bitmap.compress method. Just provide proper FileOutputStream as argument.
You can also upload image without using files, just save it to byte array and then upload as that array.
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 85, out);
byte[] myByteArray = out.toByteArray();
RequestParams params = new RequestParams();
params.put("profile_picture", new ByteArrayInputStream(myByteArray), "image.png");

Try this:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/to";
File dir = new File(file_path);
if(!dir.exists)
dir.mkdirs();
File file = new File(dir, "file.png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
and put the below permission in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Related

FireBase | Google Sign-in | How to get user's google image & download it in android phone

I tried following code to get the user's google profile pic, but this is giving only thumbnail size blur photo:
FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
This is giving me uri, which when converted to string shows following URL (URL is showing pic, but due to privacy modified few digits here):
https://lh3.googleusercontent.com/a-/AguE7mDKNdcXubEW0cMTTYzschAykXcWRQDYeMlHb8rf_g=s96-c
I am able to use this url to show picture in an ImageView using Picasso, but not sure how to download it & store in phone memory.
Picasso.get().load(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString()).fit().into(profileImage);
I tried following by converting getPhotoURL into bitmap:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(SplashActivity.this.getContentResolver(), userPhotoURLUri);
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
But this is giving me exception at the very first line:
FileNotFoundException: No content provider: for google getphotouri
Following code worked for me.
As the google profile pic doesn't contains .jpg or .png in its url therefore all other methods are not working.
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(YourActivity.this);
//Set the Image dimension here it will not reduce the image pixels
googleProfilePic = acct.getPhotoUrl().toString().replace("s96-c", "s492-c");
Glide.with(MainActivity.this).load(googleProfilePic).asBitmap().into(new BitmapImageViewTarget(imageView) {
#Override
protected void setResource(Bitmap resource) {
FileOutputStream outStream = null;
File dir = new File(myfolderPath);
String fileName = picName + ".jpg";
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.flush();
resource.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
}
Try this:
Picasso.get().load(FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl()).fit().into(profileImage);
BitmapDrawable draw = (BitmapDrawable) profileImage.getDrawable();
Bitmap bitmap = draw.getBitmap();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try{
FileOutputStream outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
}catch (Exception e) {
e.printStackTrace();
}
Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can use Android's Download Manager to have it handle the download:
// Create the Download Request
DownloadManager.Request downloadRequest = new DownloadManager.Request(myPhotoUri);
// Set the destination
// (You can include the "SubPath/FileName" as the second argument if you want the file in a sub directory)
downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, myFileName);
// Display a notification while the download is in progress and after it's completed
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Allow the media scanner to find the file
downloadRequest.allowScanningByMediaScanner();
// Enqueue the download
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(downloadRequest);
Additionally, if you want your app to perform an operation in response to the completed download, you would register a BroadcastReceiver filtering DownloadManager.ACTION_DOWNLOAD_COMPLETE Intents and check for the Download id returned by .enqueue().
Here's further information on DownloadManager and DownloadManager.Request you can use to customize your download options:
https://developer.android.com/reference/android/app/DownloadManager
https://developer.android.com/reference/android/app/DownloadManager.Request

Saving a bitmap file in android and reading back to display in Imageview

I have a bitmap file which i need to upload to my php server but as the file is very large I decided to resize it and save it. Later on I try to read it back to display resized image. But this time I am not getting the same image
Below is code for writing image and returning File
public static File savebitmap(Bitmap bmp) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "testimage.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
return f;
}
Below is code for reading and displaying
File file=ImageUtil.savebitmap(this.bitmap);
this.imgChoosenImage.setImageURI(Uri.parse(file.getAbsolutePath()));
Please tell me what exactly is going wrong here
first check the images are saved in ur path as defined, and Make sure ur giving correct path for retriving image.
I have used this below code for saving imge in gallery
String iconsStoragePath = Environment.getExternalStorageDirectory()+ File.separator;
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = null;
filePath = Environment.getExternalStorageDirectory() + File.separator + "testimage" + ".jpg";
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bmp.compress(Bitmap.CompressFormat.JPG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Failed to Create folder",
Toast.LENGTH_SHORT).show();
}
For bitmap display in imageview :
File imgFile = new File("/sdcard/Images/testimage.jpg");
//Here File file = ur file path
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

android : save svg file from web and save on a file

i want to save a svg file from web to a file and then show it from file. i use this code to save a png file :
OutputStream fos = null;
File file = new File(getApplicationContext().getCacheDir(),FilenameUtils.getBaseName(url.toString())+FilenameUtils.getExtension(url.toString()));
Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bm.compress(Bitmap.CompressFormat.PNG, 50, bos);
bos.flush();
bos.close();
what should i do for svg file ?
In theory, you should be able to do something like the following:
PictureDrawable pd = (PictureDrawable) imageView.getPicture();
Picture picture = pd.getPicture();
picture.writeToStream(os);
However you should not do this. writeToStream() is deprecated (as is createFromStream()). I presume the reason is that the format of a Picture may change in the future and any saved pictures may no longer load. If you are just using it for temporary caching while the app is running, then that may be okay.
But it would be better, as #greenapps says, to cache the original SVGs.

Need to copy image from res folder to gallery/folder

Ok, so i have Gallery Application, with lots of images in it(res/drawable).
On selection you can Set as Wallpaper button and you will have it.
Now i want to save with button SAVE TO PHONE or SD card this image selected. How can i manage that. Copying from res of application folder to Phone or SD card. Dont want to take it from ImageView but just copy the original from res to Phone.
try this code:
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".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 (Exception e) {
e.printStackTrace();
}
and add in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Follow the steps :-
Create Bitmap using BitmapFactory.decodeResource
Write the contents of Bitmap to an OutputStream using Bitmap.compress
Save the file to anywhere you want.
Code:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
file = new File(path, "image.jpg");
fOut = new FileOutputStream(file);
Bitmap bitmap = BitmapFactory.decodeResource (getResources(), R.drawable.xyz);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

How to save image file in BMP format?

the following code compress my image or it is not a BMP file:
FileOutputStream fos = new FileOutputStream(imagefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
How can I save my image in BMP format?
There's no built-in encoder for BMP according to this reference. BMP not being an overly complex format, it probably wouldn't be rocket science to write/find a Java implementation.
Hey just give the name to .bmp
Do this:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "**test.bmp**")
it'll sound that IM JUST FOOLING AROUND but try it once it'll get saved in bmp format..Cheers

Categories

Resources