I'm working with bitmap and have some problems need to help:
My app works as below:
Load JPG image file(1) from SDcard to bitmap1
Save this bitmap1 to new JPG file(2).
Load new JPG image(2) file to bitmap2
Save bitmap2 to new JPG file(3) ....
.... repeat again and again
Now I can load/save bitmap to file, but problem is quality of image reduces after load/save.
So if I do load/save stuff for 10 times, so my image become ugly.
This is my code:
private void saveBitmapToFile(String imgPath) {
Log.e("Filename-----------------", imgPath);
// Decode image file to bitmap
BitmapFactory.Options options = new BitmapFactory.Options();
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
// Get filename
long currentMili = System.currentTimeMillis();
currentName = currentMili + "";
String filePath = FOLDER_PATH + currentMili + ".jpg";
// Save bitmap to new file
try {
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You're re-compressing a lossy file format. You're going to get image artifacts doing that. If you need to do this for some reason, use a lossless format like png.
Related
I need to compress images before sending the images to the server via Android app. The images taken via camera are very large and they need to be compressed first. When a image is taken from Camera, there are some properties associated with the image like device model, aperture, location, etc.
I'm trying to compress the image, but during compression, those properties of the images are lost. Please help if there is any missing line of code or any library to compress the images without losing those properties.
private void compressImageAndAddToArrayList(Uri imageURI) {
Bitmap bm = null;
try
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
// bm = Media.getBitmap(mContext.getContentResolver(), imageLoc);
bm = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(imageURI), null, options);
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "VDMS" + File.separator + "Camera");
folder.mkdirs();
String now = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date()).toString();
String fileName = caseID + "_" + now + ".jpg";
File imageFile = new File(folder + File.separator + fileName);
FileOutputStream out = new FileOutputStream(imageFile);
bm.compress(Bitmap.CompressFormat.JPEG, 64, out); // quality ranges from 0-100
bm.recycle();
addDocumentToArrayList(String.valueOf(1), Uri.fromFile(imageFile));
}
catch (Exception e)
{
e.printStackTrace();
}
}
I am trying to get an image from phone's secondary storage.
public void downloadImage(View v) {
Bitmap myImage = GetImageBitmapFromUrl();
String path = System.getenv("SECONDARY_STORAGE") + "/";
OutputStream out = null;
try
{
File file = new File(path, "nameImage.jpg");
out = new FileOutputStream(file);
myImage.compress(Bitmap.CompressFormat.JPEG, 85, out);
out.flush();
out.close();
}
catch (Exception e)
{
}
}
When I run with debug why I get this error and it didn't receive the file also.
Error at:
myImage.compress(Bitmap.CompressFormat.JPEG, 85, out);
In the manifests file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
String photoPath = Environment.getExternalStorageDirectory()+"/photo.jpg";
and get bitmap by using code below.
The photo.jpg is the the name of the image you want to read.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
You can also use picasso image library
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
My app calls the camera to take a picture and save it into my app local directory (getApplicationContext().getFilesDir()) which works fine.
When I try to convert the picture into a bitmap using BitmapFactory the result is null. This the code I use :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
String picturePath = pictureFile.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);
Note that pictureFile was created as follows :
pictureFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
foodwarnDir /* directory */
);
Didn't you forget add permissions READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE ?
File locationOfFile = new
File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/images");
File destination= new File(locationOfFile , fileName + ".JPG");
FileInputStream fileInputStream;
fileInputStream= new FileInputStream(destination);
Bitmap img = BitmapFactory.decodeStream(fileInputStream);
OR
This is my working code in my project here:
View imageHolder = LayoutInflater.from(this).inflate(R.layout.image_item, null);
ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);
try {
String path = uri.getPath();
Bitmap bmImg = BitmapFactory.decodeFile(path);
Point p = new Point();
p.set(100, 100);
Bitmap bitmapp = waterMark(bmImg, mRefNo, p, Color.RED, 90, 60, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(this)
.load(stream.toByteArray())
.asBitmap()
.error(R.mipmap.ic_launcher)
.into(thumbnail);
mSelectedImagesContainer.addView(imageHolder);
thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps you
other helpful Links1 Link2
Create temp file:
File tempFile = File.createTempFile("temp_file, ".jpg", this.getExternalCacheDir());
get path created:
String mPath = tempFile.getAbsolutePath();
now in you activityResult
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(mPath, options);
use
data.getExtras().get("data");//for getting bitmap
Uri u = intent.getData();// for getting the Uri and get the path from uri
for getting data from your camera
Assuming you're using java.io.File class. According to Java docs function .createTempFile creates empty file on the System.
As such, this file will have only meta info without any content, with zero length, and this is probably a reason why it is not possible to extract Bitmap.
So you need to Create File Object instance instead of actual file, using new File()
You can also use WeakReference and similar to Bitmap you create if you're looking to decrease chance of memory leaks in early implementation.
I am facing a problem I cannot solve myself.
I have to capture image in my android app, and then upload that image to FTP server. Of course, I have to resize it before sending it to FTP because 2MB is definitely unacceptable size :)
I succeded in taking picture, getting its path and upload it in its full size.
This is how I upload it to server.
File file = new File(pathOfTheImage);
String testName =System.currentTimeMillis()+file.getName();
fis = new FileInputStream(file);
// Upload file to the ftp server
result = client.storeFile(testName, fis);
Is it possible, at this point, to resize or compress image in order to reduce its size and after that, to upload it to server?
Any help would be appreciated.
P.S. Sorry for my poor English!
EDIT:
Solved thanks to Alamri.
One more time, man, thank you!!!
In my application i used this before uploading the image:
1- resize,scale and decode the bitmap
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=450;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bit1 = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
return bit1;
} catch (FileNotFoundException e) {}
return null;
}
2- now let's save the resized bitmap:
private void ImageResizer(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pic");
if(!myDir.exists()) myDir.mkdirs();
String fname = "resized.im";
File file = new File (myDir, fname);
if (file.exists()){
file.delete();
SaveResized(file, bitmap);
} else {
SaveResized(file, bitmap);
}
}
private void SaveResized(File file, Bitmap bitmap) {
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
after saving the resized, scaled image. upload it using your code :
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pic/resized.im");
String testName =System.currentTimeMillis()+file.getName();
fis = new FileInputStream(file);
// Upload file to the ftp server
result = client.storeFile(testName, fis);
can anyone give me a method to how save a image's path in database and how to display the image in imageView.
You can store images and show into imageview this way.
String path = Environment.getExternalStorageDirectory().toString()+ "/Directoryname";
String imageName;
File mFolder = new File();
if (!mFolder.exists()) {
mFolder.mkdir(path);
}
imageName= "yourimagename.jpg";
//now you can store imagepath into database and imageto your sdcard so we can show image as per our requirement
File file = new File (mFolder, imageName);
if (file.exists ()) file.delete ();
Bitmap thumbnail = you can convert your image to bitmap and store into database.
try {
FileOutputStream out = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
//it will be store in your sdcard.
//for displaying image into imageview
File f = new File(path+"/"+imageName);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
iv.setImageBitmap(bitmap);
If you are finding any trouble then let me know.