I have the following code:
YuvImage yuv = new YuvImage(result.getExtractImageData(),
camera.getParameters().getPreviewFormat(),
result.getWidth(),
result.getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, result.getWidth(), result.getHeight()), 100, out);
byte[] bytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
image = RotateImage(image, rotation);
createDirectoryAndSaveFile(image, "Image_" + result.getCaptureTime() + ".jpg");
String filePath = Environment.getExternalStorageDirectory() + "/MyFolder/Image_" + result.getCaptureTime() + ".jpg";
try {
ExifInterface exif = new ExifInterface(filePath);
exif.getAttribute("UserComment");
// call this next setAttributes a few times to write all the GPS data to it.
exif.setAttribute("UserComment", String.valueOf(result.getCaptureTime()));
exif.saveAttributes();
}
catch (IOException e) {
e.printStackTrace();
}
It is supposed to punt under UserComment the result.getCaptureTime() at which it was captured from the camera. I download it to a Windows folder and I can't see the properties I just created...
What I'm doing wrong?
EDIT:
private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName)
{
File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/MyFolder/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/MyFolder/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I have made an app that uses the filter image and save in sdcard it's working good but I want to save image in two resolution high and low, I have never tried on resolution, Any one one can help that how to save in these both resolution? My code is below
private void saveBitmap(Bitmap bmp, String fileName, int resolution, String resolutionQuality) {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + fileName + ".png");
File f = new File(Environment.getExternalStorageDirectory() + "FiltureImages");
if (!f.exists()) {
File wallpaperDirectory = new File("/sdcard/FiltureImages/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/FiltureImages/"), fileName + resolutionQuality + ".png");
if (file.exists()) {
file.delete();
}
try {
fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, resolution, fos);
Toast.makeText(mActivity, "Image save successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Call like this saveBitmap(bm, "high", "low", 100, 0, "quality");
Quality range from 0 -100
Note: change Bitmap.CompressFormat.PNG to Bitmap.CompressFormat.JPEG beacuse quality works with JPEG format.
private void saveBitmap(Bitmap bmp, String fileNameHigh, String fileNameLow, int resolutionHigh, int resolutionLow, String resolutionQuality) {
File f = new File(Environment.getExternalStorageDirectory() + "FiltureImages");
if (!f.exists()) {
f.mkdirs();
}
File file = new File(f, fileNameHigh + resolutionQuality + ".png");
if (file.exists()) {
file.delete();
}
File file1 = new File(f, fileNameLow + resolutionQuality + ".png");
if (file1.exists()) {
file1.delete();
}
try {
FileOutputStream high = new FileOutputStream(file);
FileOutputStream low = new FileOutputStream(file1);
bmp.compress(Bitmap.CompressFormat.JPEG, resolutionHigh, high);
bmp.compress(Bitmap.CompressFormat.JPEG, resolutionLow, low);
Toast.makeText(this, "Image save successfully", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Image save falid", Toast.LENGTH_SHORT).show();
}
}
Create a second bitmap with an alternate resolution this way and call scaledBmp.compress() into a new file.
Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, false);
I inserted on my App a option to take a photo and save it on a directory.
But when I check the taken photo it appears turned. The horizontal photos appears vertical, and the vertical photos appears horizontal.
how can change my code and automatically rotate the photos?
My code:
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
...
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
int nh = (int) ( bitmap.getHeight() * (612.0 / bitmap.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 612, nh, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
scaled.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
viewImage.setScaleType(ScaleType.CENTER);
viewImage.setImageBitmap(scaled);
task = new getinfo();
task.execute(image_str);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
This piece helped me to do the same task
private Bitmap rotateImage(String pathToImage) {
// 1. figure out the amount of degrees
int rotation = getImageRotation();
// 2. rotate matrix by postconcatination
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
// 3. create Bitmap from rotated matrix
Bitmap sourceBitmap = BitmapFactory.decodeFile(pathToImage);
return Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), matrix, true);
}
Also check this,this and this for more details.
testButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
imageView.setImageBitmap(Bitmap);
imageView.buildDrawingCache();
Bitmap bm =imageView.getDrawingCache();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs();
String fileName = "image" + ".jpg";
File output = new File(imagesFolder, fileName);
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream fos = null;
try {
fos = getContentResolver().openOutputStream(uriSavedImage);
bm.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
}
});
First i retrieved an image from sd card to image view of resolution (640 x 480). Then again i saved the image from image view to sd card. But the image saved is of resolution is (188x113). Can anyone suggest how i can save with the same resolution. Any suggestions will be appreciable.
Try this code :
BitmapDrawable btmpDr = (BitmapDrawable) ivPic.getDrawable();
Bitmap bmp = btmpDr.getBitmap();
/*File sdCardDirectory = Environment.getExternalStorageDirectory();*/
try
{
File sdCardDirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "MeeguImages");
sdCardDirectory.mkdirs();
imageNameForSDCard = "image_" + String.valueOf(random.nextInt(1000)) + System.currentTimeMillis() + ".jpg";
File image = new File(sdCardDirectory, imageNameForSDCard);
FileOutputStream outStream;
outStream = new FileOutputStream(image);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
//Refreshing SD card
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(ViewImage.this, "Image could not be saved : Please ensure you have SD card installed " +
"properly", Toast.LENGTH_LONG).show();
}
bm.compress(CompressFormat.JPEG, 100, fos);
remove this line
Solved, This is how i achieved to save image from ImageView
/*Variable which holds Image*/
{ImageView ivBanner = "Initialise It :)";
FileOutputStream fileOutputStream = openFileOutput("ImageName" + ".jpg", MODE_PRIVATE);
Bitmap bitmap = convertToBitMap(ivBanner.getDrawable(),ivBanner.getWidth(),ivBanner.getHeight());
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fileOutputStream);
File file = getFileStreamPath("ImageName" + ".jpg");
File f = file.getAbsoluteFile();
/*Utilise your path whatever way you want*/
String localPath = f.getAbsolutePath();}
/* Covert Drawable to Bitmap*/
private Bitmap convertToBitMap(Drawable drawable, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0,0,width,height);
drawable.draw(canvas);
return bitmap;
}
I have more then 50 images in my res/drawable folder. I want to save these images to external storage and then display these image one by one in an image view/image switcher. I used below code to save single image to external storage. but i am unable to figure it out how can i save all these images to external storage altogether (at once).
public void SaveImage(){
if (!CheckExternalStorage()) {
return;
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a01);
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(path, "image1.png");
file.createNewFile();
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
Log.i(LOGTAG, "Image Written to Exterbal Storage");
} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
}
Using an answer from : https://stackoverflow.com/a/3221787/794088 with some modification to call your method SaveImage with a param
...
R.drawable drawableResources = new R.drawable();
Class<R.drawable> c = R.drawable.class;
Field[] fields = c.getDeclaredFields();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
// call save with param of resourceId
SaveImage(resourceId);
} catch (Exception e) {
continue;
}
}
...
public void SaveImage(int resId){
if (!CheckExternalStorage()) {
return;
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resID);
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(path, "image1.png");
file.createNewFile();
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
Log.i(LOGTAG, "Image Written to Exterbal Storage");
} catch (Exception e) {
Log.e("saveToExternalStorage()", e.getMessage());
}
}
I have a problem to save Bitmaps into files.
My method is like this:
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
OutputStream outStream = null;
File file = new File(bmp + ".png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, bmp + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + bmp);
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
It gives me error of file.I am calling this method like this:
Drawable d = iv.getDrawable();
Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
File file = savebitmap(bitmap);
Please help me...
I try to make some corrections on your code
I assume that you want to use filename instead of bitmap as parameter
private File savebitmap(String filename) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(filename + ".png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
// make a new bitmap from your file
Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
You can't write like this
File file = new File(bmp + ".png");
and this line is also wrong
file = new File(extStorageDirectory, bmp + ".png");
You have to give string value and not bitmap.
File file = new File(filename + ".png");
Change
File file = new File(bmp + ".png");
to
File file = new File(extStorageDirectory,"bmp.png");
like you did nearly the second time.