Image capture and upload to FTP in Android - android

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);

Related

How to compress image without losing its Metadata?

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();
}
}

Android get image in secondary storage

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);

Bad image quality when load/save bitmap

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.

insert image's path and retrieve it from SQLite

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.

Android Image resize (resample/downsample) before uploading

private void doFileUpload(){
File file1 = new File(selectedPath1);
String urlString = "http://example.com/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
I get this code from internet. it's work but when I try upload bigger file than 1Mbyte,
I face an error with filesize.
I know how to resize bitmap images and but I have no idea upload the resized bitmap image.
how can I resize and upload with filebody?
Thanks in advance
You need to not only resize the Bitmap, but you also need to encode the result as a .jpg image. Therefore, you must open the file and convert it to a Bitmap, resize the Bitmap to a smaller image, encode the image into a byte[] array, and then upload the byte[] array in the same manner as you have uploaded your file file1.
If the Bitmap is large, which it clearly is, you won't have enough heap memory to open the entire thing, so you will have to open it with BitmapFactory.Options.inSampleSize.
First, open the reduced size Bitmap:
Uri uri = getImageUri(selectedPath1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // Example, there are also ways to calculate an optimal value.
InputStream in = in = contentResolver.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
Next, encode into a byte[] array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bitmapdata = bos.toByteArray();
Finally, use reqEntity.addPart() to add the byte[] array directly, or write to a smaller file and add the file as in your current example.
This answer is based on another answer, but I had some problems with that code, so I post the edited and working code.
I did it like this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.outWidth = 50; //pixels
options.outHeight = 50; //pixels
InputStream in = context.getContentResolver().openInputStream(data.getData()); // here, you need to get your context.
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bitmapdata = baos.toByteArray();
Notice that, data is the returned data from the Intent you use to get the file. If you already have the file path, just use that...
And now, when you are creating the HTTP Entity, add:
FormBodyPart fbp = new FormBodyPart("image", new ByteArrayBody(baos.toByteArray(), "image/jpeg", "image"));
entity.addPart(fbp);
Also, notice that you need a MultipartEntity to upload files.

Categories

Resources