My app uses the following piece of code to write out images I have resized into the app's data folder:
private void writeImage(Bitmap bmp, String filename)
{
try
{
FileOutputStream stream = openFileOutput(filename, MODE_WORLD_WRITEABLE);
bmp.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I am able to read them in a file browser (ddms) and can confirm they appear to have been written.
However, any attempt to load the images results in non-null bitmaps with width and height of -1. I am using the following code to load them:
imageList = getFilesDir().list();
Bitmap bmp = null;
for(String img : imageList)
{
try {
bmp = BitmapFactory.decodeStream(openFileInput(img));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: On further inspection, it seems, after conversion the images are of density 160 (and not 240 as they should be) also, after testing a working application it seems the -1 mWidth and -1 mHeight on the bitmaps is irrelevent.
I had same problem.my data folder given smallest image.and cursor return null pointer exception on my getDestination method.then i fixed like it
public void captureNewPhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
targetFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
targetUri = Uri.fromFile(targetFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 12);
}
And i use like in onActivityResult();
BitmapFactory.Options options = new BitmapFactory.Options();
networkBitmap = BitmapFactory.decodeFile(targetUri.getPath(),
options);
//ImageDialog(networkBitmap);
//String path = getRealPathFromUri(this, Uri.parse(targetUri.getPath()));
String myDeviceModel = android.os.Build.MODEL;
deviceName = Build.MANUFACTURER;
if (myDeviceModel.equals("GT-I9500")) {
} else if (deviceName.contains("samsung")) {
} else {
exif = ReadExif(targetUri.getPath());
if (exif.equals("6")) {
matrixx.postRotate(90);
} else if (exif.equals("7")) {
matrixx.postRotate(-90);
} else if (exif.equals("8")) {
matrixx.postRotate(-90);
} else if (exif.equals("5")) {
matrixx.postRotate(-90);
}
//matrixx.postRotate(-90);
}
networkBitmap = Bitmap.createBitmap(networkBitmap, 0, 0, networkBitmap.getWidth(), networkBitmap.getHeight(), matrixx, true);
Log.e("Taget File ", "Size " + targetFile.length());
if (networkBitmap != null) {
ImageSetting(networkBitmap, System.currentTimeMillis() + filename);
}
public void ImageSetting(Bitmap imageBitmap, final String fileName) {
networkBitmap = imageBitmap;
organizator(networkBitmap, fileName);
networkBitmap = null;
}` public void tamamlandiOndenFoto(Bitmap turnedBitmap, String filename) {
frontFotoFile = storeBitmap(networkBitmap, filename);
ondenFotoPath = ondenFoto.getAbsolutePath();
ondenFotoImageView.setImageBitmap(turnedBitmap);
}`
public File storeBitmap(Bitmap bp, String fileName) {
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File dest = new File(sd, fileName);
if (bp != null) {
try {
FileOutputStream out = new FileOutputStream(dest);
bp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Alinan hata ", " Catch hata ", e);
}
return dest;
} else {
return null;
}
}
I hope give you any idea for your problem.
Related
I'm processing about 4 images / seconds from camera preview, save it to png File and send it to a server.
I couldn't yet identify why, but 1 time out of 2 the current session will store the .png as full black pictures. the File size is also very small (3kb vs the usual 700kb).
Here's how I store the Bitmap as a PNG file :
public static File SaveImagePNG(Bitmap subimg, String path, String filename) {
FileOutputStream out = null;
File sd = new File(path);
boolean success = true;
if (!sd.exists()) {
success = sd.mkdir();
}
if (success) {
File dest = new File(sd, filename);
try {
out = new FileOutputStream(dest);
if (subimg != null) {
// PNG is a lossless format, the compression factor (100) is ignored
subimg.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
}
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
} finally {
try {
if (out != null) {
out.close();
Log.d(TAG, "OK!!");
}
} catch (IOException e) {
Log.d(TAG, e.getMessage() + "Error");
e.printStackTrace();
}
}
return dest;
}
return null;
}
and here's how I call it :
val pathFilePNG = Environment.getExternalStorageDirectory().toString() + "/images"
requestParams[0]?.bitmapRGB?.setHasAlpha(false)
val imageFaceRGBFile = BitmapUtils.SaveImagePNG(requestParams[0]?.bitmapRGB, pathFilePNG, "faceRGB.png")
The preview on the phone looks good before sending the file, but once it is received on the server and reloaded on the mobile is rotated vertical images.
public static File saveBitmapTemporarily(Bitmap finalBitmap, int extension, ExifInterface oldExif) {
String root = Environment.getExternalStorageDirectory().toString();
FileUtils.createFolder(new File(Environment.getExternalStorageDirectory() + BuildConfig.STORAGE_DIR));
File myDir = new File(root + BuildConfig.STORAGE_DIR + "/");
myDir.mkdirs();
String fname;
if (extension == IMAGE_FORMAT_JPG_JPEG) {
fname = "file-reduced.jpg";
} else {
fname = "file-reduced.png";
}
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
if (extension == IMAGE_FORMAT_JPG_JPEG) {
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
} else {
finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
}
out.flush();
out.close();
} catch (Exception e) {
if (BuildConfig.DEBUG)
e.printStackTrace();
}
return file;
}
Welcome to Stack Overflow #kiketurry... Here you have what I did to solve this problem. You should store the width and height dimension in the exif data of the photo so that the server knows how to orient it, but it can only be in jpg
if (extension == IMAGE_FORMAT_JPG_JPEG) {
ExifInterface oldExif = null;
try {
oldExif = new ExifInterface(file.getAbsolutePath());
ExifInterface newExif;
newExif = new ExifInterface(file.getAbsolutePath());
newExif.setAttribute("ImageLength", String.valueOf(finalBitmap.getHeight()));
newExif.setAttribute("ImageWidth", String.valueOf(finalBitmap.getWidth()));
if (oldExif != null) {
String exifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION);
if (exifOrientation != null) {
newExif.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrientation);
}
}
newExif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
}
}
I hope it helps.
At start up of my app I want to extract my images (if they does not exists) from drawable folder to internal app folder to use later with FileProvider. Images have dimensions 2000*2000 and average size 380kb, format png.
Those images are not to be displayed (smaller ones are used to display). They are only for file sharing and I have to keep their original size.
I get out of memory at calling
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResID);
Code
private void extractImages() {
TypedArray imgs = getResources().obtainTypedArray(R.array.smile_list_share);
File imagePath = new File(getFilesDir(), "images");
File checkImage;
for (int i = 0; i < imgs.length(); i++) {
int imageResID = imgs.getResourceId(i, 0);
if (imageResID > 0) {
String name = getResources().getResourceEntryName(imageResID);
checkImage = new File(imagePath, name + ".png");
if (!checkImage.exists()) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResID);
boolean b = saveBitmapToFile(imagePath, name + ".png", bm, Bitmap.CompressFormat.PNG, 100);
Log.e("mcheck","saved "+b+", file "+name);
Log.e("mcheck", "file does not exists " + name);
} else {
Log.e("mcheck", "file exists " + name);
}
} else {
Log.e("mcheck", "ERROR " + i);
}
}
imgs.recycle();
}
public boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format, quality, fos);
bm.recycle();
fos.close();
return true;
} catch (IOException e) {
Log.e("app", e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
You have to call recycle on your bitmap object everytime you are done with it.
Here is a good guide on how to manipulate bitmaps efficiently
https://developer.android.com/training/displaying-bitmaps/load-bitmap.html
I found that I dont need to create bitmap object at all. It is possible to obtaine intput stream from getResourses directly.
public boolean saveBitmapToFile(File dir, String fileName, int imageResourse) {
File imageFile = new File(dir, fileName);
FileOutputStream fos = null;
InputStream inputStream = null;
try {
fos = new FileOutputStream(imageFile);
inputStream = getResources().openRawResource(imageResourse);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
inputStream.close();
fos.close();
return true;
} catch (IOException e) {
Log.e("app", e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
i need to save an image to a custom folder in my phone.
my code is
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
FileOutputStream outStream = null;
try {
Random generator = new Random();
int n = 0000;
n = generator.nextInt(n);
String fName = "Image" + n + ".jpg";
outStream = new FileOutputStream(String.format(fName));
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
}
not working
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
if(bitmap!=null){
File file=new File(Environment.getExternalStorageDirectory()+"/dirr");
if(!file.isDirectory()){
file.mkdir();
}
file=new File(Environment.getExternalStorageDirectory()+"/dirr",System.currentTimeMillis()+".jpg");
try
{
FileOutputStream fileOutputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
catch(IOException e){
e.printStackTrace();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
}
Dont forget to add permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can find ans from below code
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
Bitmap m_bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
String destinationPath = Environment.getExternalStorageDirectory() + "/" + "Image.jpg";
if (m_bitmap != null || destinationPath != null)
{
FileOutputStream m_out = new FileOutputStream(destinationPath);
m_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, m_out);
}
}
Hope this code helps you
You first have to create the destination folder you want to save the file into. So, in your Android sdk folder, you create the MediaFiles folder. In this folder you can then create your file.
Here's some code you can try.
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
FileOutputStream outStream = null;
try {
Random generator = new Random();
int n = 0000;
n = generator.nextInt(n);
String fName = "Image" + n + ".jpg";
outStream = new FileOutputStream(GetPathForFileName(fName));
outStream.write(data);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
}
private String GetPathForFileName(String fileName)
{
try
{
String savePath = GetSaveFolderFromConfiguration();
File file = new File(savePath + "/" + fileName);
return savePath + "/" + fileName;
}
catch (Exception ex)
{
ExceptionForm.ShowException(ex);
}
return null;
}
public static String GetSaveFolderFromConfiguration() throws Exception
{
String path = Environment.getExternalStorageDirectory().toString() + "/MediaFiles";
File f = new File(path);
if (f.exists())
return path;
else
f.mkdir();
return path;
}
I am making an android apps that can take photos. I have written some codes to save the photos taken by the app. The directory that I want to save the file is in the internal storage and in the folder named DCIM. However, the app crashes everytime I tried to save the photo. Below is my code:
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"sdcard/DCIM/jgjk.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Is there anything wrong with the code?
This will work fine
Getting Bitmap in onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode==PIC_CROP)
{
if(resultCode==RESULT_OK)
{
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap bmp = extras.getParcelable("data");
savePhoto(bmp);
}
}
}
}
public void savePhoto(Bitmap bmp)
{
dir = Environment.getExternalStorageDirectory().toString() + "/DCIM/";
File newdir = new File(dir);
newdir.mkdirs();
FileOutputStream out = null;
//file name
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
File imageFileName = new File(newdir, "crop_"+date.toString() + ".jpg");
try
{
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
out = null;
} catch (Exception e)
{
e.printStackTrace();
}
}
public String fromInt(int val)
{
return String.valueOf(val);
}