i want to upload Image in Same Size choosed From Gallary.i.Uploaded to the server ..But Image is uploaded On Server like Compressed....like This Image Below
i want to upload Image in Same Size ...or how to set Cropped Intent In This Methode
here Is My Code To Adjust Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 123987:
if (resultCode == RESULT_OK) {
try {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Log.d("selectedImagePath", "selectedImagePath = " + selectedImagePath);
ParseImage _ParseImage = new ParseImage();
_ParseImage.activityContext = this;
_ParseImage.execute(selectedImagePath);
} catch (Exception e) {
// TODO: handle exception
}
}
break;
case 1234:
if (resultCode == RESULT_OK) {
try {
final_bitmap = null;
String realPath = Environment.getExternalStorageDirectory() + "/" + fileName;
selectedImagePath = realPath;
new BitmapFactory();
Bitmap btmp = setBitmap(selectedImagePath);
/*String path = selectedImagePath.toLowerCase();
if (path.contains("dcim") && path.contains("camera")) {
btmp = RotateBitmap(btmp, 90);
}*/
int o_width = btmp.getWidth();
int o_height = btmp.getHeight();
// w=1840, h=3264
float large_image_ratio = 300.00f;
//Log.d("orignal_image", "orignal_image = " + o_width + " , " + o_height);
if (o_width > o_height) {
if (o_width >= large_image_ratio) {
float temp_w = (float)o_width/(float)large_image_ratio;
//int temp_h = o_height/large_image_ratio;
//Log.d("temp_w", "temp_w = " + temp_w);
int scales_width = (int) large_image_ratio;
int scales_height = (int) Math.round(o_height/temp_w);
//Log.d("scale_image-if", "scale_image-if = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
} else {
if (o_height >= large_image_ratio) {
//int temp_w = o_width/large_image_ratio;
float temp_h = (float)o_height/(float)large_image_ratio;
//Log.d("temp_h", "temp_h = " + temp_h);
int scales_width = (int) Math.round(o_width/temp_h);
int scales_height = (int) large_image_ratio;
//Log.d("scale_image-else", "scale_image-else = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
}
img.setImageBitmap(final_bitmap);
Image_into_Byte(final_bitmap);
img.setVisibility(View.VISIBLE);
btn_upload.setEnabled(true);
} catch (Exception e) {
// TODO: handle exception
}
}
break;
}
}
public class ParseImage extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
protected Context activityContext;
#Override
protected void onPreExecute() {
try {
final_bitmap = null;
this.dialog = new ProgressDialog(activityContext, AlertDialog.THEME_HOLO_LIGHT);
//this.dialog.setTitle(title);
this.dialog.setMessage("Loading Image");
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.show();
} catch (Exception e) {
// TODO: handle exception
}
}
protected String doInBackground(String... image_path) {
try {
new BitmapFactory();
Bitmap btmp = setBitmap(selectedImagePath);
/*String path = selectedImagePath.toLowerCase();
if (path.contains("dcim") && path.contains("camera")) {
btmp = RotateBitmap(btmp, 90);
}*/
int o_width = btmp.getWidth();
int o_height = btmp.getHeight();
// w=1840, h=3264
float large_image_ratio = 300.00f;
//Log.d("orignal_image", "orignal_image = " + o_width + " , " + o_height);
if (o_width > o_height) {
if (o_width >= large_image_ratio) {
float temp_w = (float)o_width/(float)large_image_ratio;
//int temp_h = o_height/large_image_ratio;
//Log.d("temp_w", "temp_w = " + temp_w);
int scales_width = (int) large_image_ratio;
int scales_height = (int) Math.round(o_height/temp_w);
//Log.d("scale_image-if", "scale_image-if = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
} else {
if (o_height >= large_image_ratio) {
//float temp_w = o_width/large_image_ratio;
float temp_h = (float)o_height/(float)large_image_ratio;
//Log.d("temp_h", "temp_h = " + temp_h);
int scales_width = (int) Math.round(o_width/temp_h);
int scales_height = (int) Math.round(o_width/temp_h);
//Log.d("scale_image-else", "scale_image-else = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return "complete";
}
#Override
protected void onPostExecute(String result) {
try {
this.dialog.cancel();
SaveBitmap(final_bitmap);
// final_bitmap
img.setImageBitmap(final_bitmap);
Image_into_Byte(final_bitmap);
btn_upload.setEnabled(true);
} catch (Exception e) {
// TODO: handle exception
}
}
}
// crop intent function
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 2);
}
get uri from gallery selected image
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
use this function when get image from gallery and camera :-
// camera on activityresult
cropCapturedImage(Uri.fromFile(file));
// gallery
cropCapturedImage(Uri.fromFile(getRealPathFromURI(data.getData())));
You should make Base64 encoded string of Bitmap and send this image string to server via NameValuePair with url. Use AsyncTask<...> for uploading image like for example:
private class ImgUploadingTask extends AsyncTask<String, Void, String>
{
//do your stuff onPreExecute()
#Override
protected String doInBackground(String... params)
{
try
{
String imageDataString = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(server_url);
List<NameValuePair> list = new ArrayList<NameValuePair>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
imageDataString = Base64.encodeToString(data, Base64.DEFAULT);
list.add(new BasicNameValuePair("image", imageDataString));
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
String response = EntityUtils.toString(entity);
Log.d("Response ", response);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
//do your stuff onPostExecute()
After this you have to set your server side code, accept this Base64 encoded String and decode it on server side to get real image.
Related
how can I compress image size before uploading this is my code
I want to compress image size before its uploaded to WordPress site
I am using WordPress rest API in my android app
how can I compress image size before uploading this is my code
I want to compress image size before its uploaded to WordPress site
I am using WordPress rest API in my android app
// getting images selected from gallery for post and sending them to server
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FilePickerConst.REQUEST_CODE_PHOTO:
if (resultCode == Activity.RESULT_OK && data != null) {
imagePaths = new ArrayList<>();
imageRequestCount = 1;
imagePaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
if (SettingsMain.isConnectingToInternet(context)) {
if (imagePaths.size() > 0) {
btnSelectPix.setEnabled(false);
AsyncImageTask asyncImageTask = new AsyncImageTask();
asyncImageTask.execute(imagePaths);
}
}
} else {
btnSelectPix.setEnabled(true);
Toast.makeText(context, settingsMain.getAlertDialogMessage("internetMessage"), Toast.LENGTH_SHORT).show();
}
break;
}
}
private void adforest_uploadImages(List<MultipartBody.Part> parts) {
Log.d("info image parts", parts.toString());
String ad_id = Integer.toString(addId);
RequestBody adID =
RequestBody.create(
okhttp3.MultipartBody.FORM, ad_id);
Log.d("info SendImage", addId + "");
final Call<ResponseBody> req = restService.postUploadImage(adID, parts, UrlController.UploadImageAddHeaders(context));
req.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Log.v("info Upload", response.toString());
JSONObject responseobj = null;
try {
responseobj = new JSONObject(response.body().string());
Log.d("info UploadImage object", "" + responseobj.getJSONObject("data").toString());
if (responseobj.getBoolean("success")) {
adforest_updateImages(responseobj.getJSONObject("data"));
int selectedImageSize = imagePaths.size();
int totalSize = currentSize + selectedImageSize;
Log.d("info image2", "muImage" + totalSize + "imagePaths" + totalUploadedImages);
if (totalSize == totalUploadedImages) {
adforest_UploadSuccessImage();
imagePaths.clear();
paths.clear();
if (allFile.size() > 0) {
for (File file : allFile) {
if (file.exists()) {
if (file.delete()) {
Log.d("file Deleted :", file.getPath());
} else {
Log.d("file not Deleted :", file.getPath());
}
}
}
}
}
} else {
adforest_UploadFailedImage();
Toast.makeText(context, responseobj.get("message").toString(), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
adforest_UploadFailedImage();
e.printStackTrace();
} catch (IOException e) {
adforest_UploadFailedImage();
e.printStackTrace();
}
btnSelectPix.setEnabled(true);
} else {
adforest_UploadFailedImage();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("info Upload Image Err:", t.toString());
if (t instanceof TimeoutException) {
adforest_UploadFailedImage();
// adforest_requestForImages();
}
if (t instanceof SocketTimeoutException) {
adforest_UploadFailedImage();
// adforest_requestForImages();
//
} else {
adforest_UploadFailedImage();
// adforest_requestForImages();
}
}
});
}
private void adforest_UploadFailedImage() {
progress_bar.setVisibility(View.GONE);
loadingLayout.setVisibility(View.GONE);
Gallary.setVisibility(View.VISIBLE);
Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_black_24dp, 0, 0, 0);
Gallary.setText("" + 0);
Gallary.setTextColor(Color.parseColor("#a0a0a0"));
tv_done.setVisibility(View.VISIBLE);
tv_done.setTextColor(Color.parseColor("#ff0000"));
tv_done.setText(progressModel.getFailMessage());
btnSelectPix.setEnabled(true);
Toast.makeText(context, progressModel.getFailMessage(), Toast.LENGTH_SHORT).show();
}
private void adforest_UploadSuccessImage() {
progress_bar.setVisibility(View.GONE);
Gallary.setVisibility(View.VISIBLE);
loadingLayout.setVisibility(View.GONE);
Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_green_24dp, 0, 0, 0);
Gallary.setText(totalFiles + "");
tv_done.setText(progressModel.getSuccessMessage());
Toast.makeText(context, progressModel.getSuccessMessage(), Toast.LENGTH_SHORT).show();
btnSelectPix.setEnabled(true);
tv_done.setTextColor(Color.parseColor("#20a406"));
}
private MultipartBody.Part adforestst_prepareFilePart(String fileName, Uri fileUri) {
File finalFile = new File(SettingsMain.getRealPathFromURI(context, fileUri));
allFile.add(finalFile);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
finalFile
);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(fileName, finalFile.getName(), requestFile);
}
private File adforest_rotateImage(String path) {
File file = null;
Bitmap bitmap = BitmapFactory.decodeFile(path);
ExifInterface ei = null;
try {
ei = new ExifInterface(path);
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap = null;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bitmap;
}
file = new File(getRealPathFromURI(getImageUri(rotatedBitmap)));
allFile.add(file);
return file;
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private class AsyncImageTask extends AsyncTask<ArrayList<String>, Void, List<MultipartBody.Part>> {
ArrayList<String> imaagesLis = null;
boolean checkDimensions = true, checkImageSize;
#SafeVarargs
#Override
protected final List<MultipartBody.Part> doInBackground(ArrayList<String>... params) {
List<MultipartBody.Part> parts = null;
imaagesLis = params[0];
totalFiles = imaagesLis.size();
for (int i = 0; i < imaagesLis.size(); i++) {
parts = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
Log.d("info image", currentDateandTime);
checkDimensions = true;
checkImageSize = true;
if (adPostImageModel.getDim_is_show()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imaagesLis.get(i), options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
if (imageHeight > Integer.parseInt(adPostImageModel.getDim_height()) &&
imageWidth > Integer.parseInt(adPostImageModel.getDim_width())) {
checkDimensions = true;
} else {
checkDimensions = false;
runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getDim_height_message(), Toast.LENGTH_SHORT).show());
}
}
File file = new File(imaagesLis.get(i));
long fileSizeInBytes = file.length();
Integer fileSizeBytes = Math.round(fileSizeInBytes);
if (fileSizeBytes > Integer.parseInt(adPostImageModel.getImg_size())) {
checkImageSize = false;
runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getImg_message(), Toast.LENGTH_SHORT).show());
} else {
checkImageSize = true;
}
if (checkImageSize && checkDimensions) {
File finalFile1 = adforest_rotateImage(imaagesLis.get(i));
// File finalFile1 =new File(imaagesLis.get(i));
Uri tempUri = SettingsMain.decodeFile(context, finalFile1);
parts.add(adforestst_prepareFilePart("file" + i, tempUri));
adforest_uploadImages(parts);
}
}
return parts;
}
You can use this scale down function
public static Bitmap scaleDown(Bitmap your_image, float YOUR_SIZE,boolean filter) { //filter false = Pixelated, true = Smooth
float ratio = Math.min( YOUR_SIZE/ your_image.getWidth(),
YOUR_SIZE/ your_image.getHeight());
int width = Math.round( ratio * your_image.getWidth());
int height = Math.round( ratio * your_image.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(your_image, width, height,
filter);
return newBitmap;
}
You already have the mechanism for compressing in your code:
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
See the documentation:
https://developer.android.com/reference/android/graphics/Bitmap.html#public-methods_1
Basically you need to change 100 to a lower number in order to compress the image.
Generally I had code for Image picker and I had following code in a Fragment but whenever I run the data is sent to server but image is not sent.
private void startingCameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("====onActivityResult");
if (requestCode == SELECT_PICTURE && resultCode == getActivity().RESULT_OK) {
selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getActivity(), selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
filepath = cursor.getString(column_index);
System.out.println("file path is :----" + filepath);
System.out.println("file selectedImageUri :----" + selectedImageUri);
imageview_pic.setVisibility(View.VISIBLE);
Picasso.with(getActivity()).load(selectedImageUri).fit().into(imageview_pic);
} else if (requestCode == CAMERA_PIC_REQUEST && resultCode == getActivity().RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);
// thumbnail.createScaledBitmap(thumbnail,1024,768,true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// ivImage.setImageBitmap(thumbnail);
imageview_pic.setVisibility(View.VISIBLE);
System.out.println("===Image Path : " + destination);
System.out.println("===thumbnail : " + thumbnail);
filepath = String.valueOf(destination);
Log.d("Image path",filepath);
imageview_pic.setImageBitmap(thumbnail);
} else {
}
}
//----------------------------------------------------------------------------------------------------------
class postadd extends AsyncTask<String, String, JSONObject>
{
String title = ettitle.getText().toString();
String name = etname.getText().toString();
String city = etcity.getText().toString();
String district = text.getText().toString();
String taluka = text1.getText().toString();
String contact = etcontact.getText().toString();
String price = etprice.getText().toString() + " / " + item;
String details = etdetails.getText().toString();
// String img=selectedImageUri.getPath().toString();
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "Image Upload URL";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "result";
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> map = new HashMap<>();
map.put("file_upload",filepath);
map.put("add_title", title);
map.put("cat", cat_id);
map.put("sub_cat", finalsubcatid);
map.put("add_price", price);
map.put("add_description", details);
map.put("add_name", name);
map.put("add_phone", contact);
map.put("add_city", city);
map.put("add_district", district);
map.put("add_taluka", taluka);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", map);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (pd != null && pd.isShowing())
{
pd.dismiss();
}
if (json != null) {
/* Toast.makeText(SignUp.this, json.toString(),
Toast.LENGTH_LONG).show();
*/
try {
// result = json.getInt(TAG_SUCCESS);
result = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(result.equals("true"))
{
Toast.makeText(getActivity(),"Add Posted Successfull",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(),"Post Not Done...",Toast.LENGTH_SHORT).show();
}
}
}
The above code is used in PostAddFragment from where Camera intent is call to click and when post add button is hit it upload image to server.
You cannot send image like this, you may need to send it as an Multipart Entity or you can send it as a String also using Base64 encoding which can be hectic.
String path = Utils.getPath(getApplicationContext(), uri);
Bitmap bitmap = BitmapFactory.decodeFile(path);
byte[] imageBytes = getBytesFromBitmap(bitmap);
final String image = Base64.encodeToString(imageBytes, Base64.DEFAULT);
image will be your string of image
map.put("image ", image );
and on server side you have to get it as s String and decode it using Base64 decoder
Currently I am able to upload an existed image in the sdcard to my server. I'm a total newbie in Android programming world and I was wondering how do I dynamically grab the newly taken image and submit it to the server?
This is what I have so far for my onClick event
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
new Thread(new Runnable() {
public void run() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
//hard code
String path = mediaStorageDir.getPath() + "/" + "IMG_20000106_124322.jpg";
int response= uploadFile(path);
System.out.println("RES : " + response);
}
}).start();
}});
This is the codes for my camera functions
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs())
{
Log.d("nypdImages", "Oops! Failed create " + "nypdImages" + " directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String path = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";
outStream = new FileOutputStream(String.format(path, System.currentTimeMillis()));
outStream.write(arg0);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
//VuzixCamera.super.onBackPressed();
}
camera.startPreview();
}};
Hope this answer will help you.
Take A new Picture Code:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class CameraUtil extends Activity {
private final static int REQUEST_TAKE_PHOTO=200;
private final String TAG = "Camera";
String mCurrentPhotoPath;
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(! isDeviceSupportCamera()){
Log.e(TAG,"Camera Not Supported");
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
}
else{
dispatchTakePictureIntent();
}
}
private void dispatchTakePictureIntent() {
Log.i(TAG,"Dispatch Take Picture Intent");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.i(TAG,"Error occurred while creating the File");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
File file= new File(path);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && path!=null && file.length()>0) {
Intent returnFromCameraIntent = new Intent();
returnFromCameraIntent.putExtra("picturePath",path);
setResult(RESULT_OK,returnFromCameraIntent);
finish();
Log.i(TAG,"Camera Closed");
}else{
Log.i(TAG,"On Result CANCEL");
// cancelled Image capture
try{
/*delete Temperory created file*/
file.delete();
}catch(Exception e){
e.printStackTrace();
}
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
Log.i(TAG,"Image Capture Cancelled");
}
galleryAddPic();
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
String imageFileName = "CAMERA_" + timeStamp + "_WA0001";
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyApp"+ File.separator);
if(!root.exists()){
root.mkdirs();
}
// File storageDir = Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
root /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
path=""+image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
}
Choose Existing Picture Code:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class GalleryUtil extends Activity{
private final static int RESULT_LOAD_GALLERY=100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "Gallery_Image";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_GALLERY);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}else{
Log.i(TAG,"Image Capture Cancelled");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED,returnFromGalleryIntent);
finish();
}
}
}
Convert Image to Base64 String:
public class Base64Utils {
private static final String TAG = "Base64Utils";
private String picturePath;
private String base64;
public Base64Utils(String picturePath) {
this.picturePath = picturePath;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public String getBase64() {
FileInputStream fis11=null;
try {
fis11 = new FileInputStream(picturePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos11 = new ByteArrayOutputStream();
byte[] buf = new byte[8096];
try {
for (int readNum; (readNum = fis11.read(buf)) != -1;) {
bos11.write(buf, 0, readNum);
}
} catch (IOException ex) {
ex.printStackTrace();
}
bytes = bos11.toByteArray();
base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
return base64;
}
public void setBase64(String base64) {
this.base64 = base64;
}
}
Main Activity Code: Choose or Take Picture, convert it to base64 string and Send Base64 String to Server.
public class CapatureImage extends Activity implements View.OnClickListener {
private final String TAG = "CapatureImage";
String picturePath;
String base64 = null,
private ImageButton image;
// for popup
private PopupWindow pop;
private final int GALLERY_ACTIVITY_CODE = 200;
private final int CAMERA_ACTIVITY_CODE = 300;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CapatureImage);
configureComponent();
}
private void configureComponent() {
image = (ImageButton) findViewById(R.id.image);
image.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.image:
initiatePopupWindow();
break;
case R.id.button_camera_dialog:
Intent camera_Intent = new Intent(this.getApplicationContext(),
CameraUtil.class);
pop.dismiss();
this.startActivityForResult(camera_Intent, CAMERA_ACTIVITY_CODE);
break;
case R.id.button_gallery_dialog:
Intent gallery_Intent = new Intent(this.getApplicationContext(),
GalleryUtil.class);
pop.dismiss();
this.startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
break;
case R.id.button_cancel_dialog:
pop.dismiss();
break;
case R.id.button_remove_dialog:
Log.i(TAG, "Remove Picture");
image.setImageResource(R.drawable.icon_781q);
picturePath=null;
pop.dismiss();
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64();
//send this base64 string to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
if (requestCode == CAMERA_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
// Log.i("Camera_Activity", data.toString());
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64(); //send this base64 to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
}// onActivityResult
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) EngineerStatus_Update.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialoge_choosephoto,
(ViewGroup) findViewById(R.id.photo_popup));
if (picturePath != null && !picturePath.isEmpty()) {
Log.i(TAG, "Image Exist..Add Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.VISIBLE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
} else {
Log.i(TAG, "No Image..remove Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.GONE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
}
// component for popup
gallery = (Button) layout.findViewById(R.id.button_gallery_dialog);
gallery.setOnClickListener(this);
camera = (Button) layout.findViewById(R.id.button_camera_dialog);
camera.setOnClickListener(this);
cancel = (Button) layout.findViewById(R.id.button_cancel_dialog);
cancel.setOnClickListener(this);
pop.showAtLocation(layout, Gravity.CENTER, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
void displayImage(String path) {
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
image.setScaleType(ScaleType.CENTER_CROP);
}
}
}
there is two classes upload and main_activity.And i here put it's xml file
public class MainActivity extends Activity {
final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
private static final String TAG = "CaptureImage.java";
public static ImageView showImg = null;
static String uploadFilePath = " ";
static String Path;
static int delete_image_id = 0;
static TextView imageDetails = null;
// FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
static Cursor cursor = null;
public ProgressDialog dialog_upload = null;
public String s_name;
public String s_Adress;
int serverResponseCode = 0;
TextView shift_display;
Uri imageUri = null;
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("VALUES", "It is Working");
String fileName = "Camera_Example.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
};
MainActivity CameraActivity = null;
Upload upload;
Button outlet_names_show;
double latitude;
double longitude;
OnClickListener oclBtnOk3 = new OnClickListener() {
#Override
public void onClick(View v) {
if (showImg.getDrawable() == null) {
Toast.makeText(MainActivity.this, " Picture was not captured ",
Toast.LENGTH_SHORT).show();
} else {
upload_prescription();
// CallSummery.flag_bt_merchan=true;
}
}
};
private Button buttonback;
/**
* ********* Convert Image Uri path to physical path *************
*/
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
int imageID = 0;
try {
/*********** Which columns values want to get *******/
String[] proj = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION};
cursor = activity.getContentResolver().query(imageUri, proj, null,
null, null);
// Get Query Data
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int file_ColumnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// int orientation_ColumnIndex = cursor.
// getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
int size = cursor.getCount();
/******* If size is 0, there are no images on the SD Card. *****/
if (size == 0) {
// imageDetails.setText("No Image");
} else {
if (cursor.moveToFirst()) {
imageID = cursor.getInt(columnIndex);
delete_image_id = imageID;
Path = cursor.getString(file_ColumnIndex);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// Return Captured Image ImageID ( By this ImageID Image will load from
// sdcard )
return "" + imageID;
}
protected void onCreate(Bundle savedInstanceState) {
MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraActivity = this;
showImg = (ImageView) findViewById(R.id.showImg);
upload = new Upload(MainActivity.this);
final Button photo = (Button) findViewById(R.id.photo);
final Button upload = (Button) findViewById(R.id.upload);
photo.setOnClickListener(oclBtnOk);
upload.setOnClickListener(oclBtnOk3);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (imageUri != null) {
outState.putString("cameraImageUri", imageUri.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
imageUri = Uri
.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void upload_prescription() {
dialog_upload = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
createDirectoryIfNeeded();
upload.uploadFile(uploadFilePath);
}
}).start();
}
private void createDirectoryIfNeeded() {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Capturetemp");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
}
public void copy(String lo, String lan) throws JSONException {
String sdCard = Environment.getExternalStorageDirectory().toString();
Random ran = new Random();
uploadFilePath = sdCard + "/Capturetemp/" + ran.toString() + ".jpg";
File sourceLocation = new File(Path);
File targetLocation = new File(uploadFilePath);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if (actionChoice == 1) {
if (sourceLocation.renameTo(targetLocation)) {
Log.v(TAG, "Move file successful.");
} else {
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else {
// make sure the target file exists
if (sourceLocation.exists()) {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
} else {
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
/*********** Load Captured Image And Data Start ***************/
String imageId = convertImageUriToFile(imageUri, CameraActivity);
// Create and excecute AsyncTask to load capture image
new LoadImagesFromSDCard(MainActivity.this).execute(""
+ imageId);
/*********** Load Captured Image And Data End ****************/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBackPressed() {
}
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
Context context;
Bitmap mBitmap;
private ProgressDialog loadingdailog;
public LoadImagesFromSDCard(MainActivity context) {
this.context = context;
}
#Override
protected void onPreExecute() {
loadingdailog = new ProgressDialog(context);
loadingdailog.setMessage("Loading Image.....");
loadingdailog.show();
}
// Call after onPreExecute method
#Override
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
uri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
+ urls[0]);
/************** Decode an input stream into a bitmap. *********/
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
/********* Creates a new bitmap, scaled from an existing bitmap. ***********/
newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
true);
// SaveIamge(newBitmap);
bitmap.recycle();
if (newBitmap != null) {
mBitmap = newBitmap;
}
}
} catch (IOException e) {
// Error fetching image, try to recover
/********* Cancel execution of this task. **********/
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (loadingdailog.isShowing() && loadingdailog != null) {
loadingdailog.dismiss();
loadingdailog = null;
}
if (mBitmap != null) {
showImg.setImageBitmap(mBitmap);
}
}
}
}
upload class
public class Upload {
protected MainActivity context;
ProgressDialog dialog = null;
int serverResponseCode = 0;
String uploadFilePath = null;
String uploadFileName = null;
String msg = null;
String upLoadServerUri = "http://fileuploadpath";
public Upload(MainActivity context) {
this.context = context;
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("photo", fileName);
// conn.setRequestProperty("session_id","13");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
try {
readStream(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
context.runOnUiThread(new Runnable() {
public void run() {
context.dialog_upload.dismiss();
Toast.makeText(context, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
fileInputStream.close();
} catch (MalformedURLException ex) {
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// context.dialog.dismiss();
e.printStackTrace();
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
// context.dialog.dismiss();
return serverResponseCode;
}
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.e("tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/showImg"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="bla bla" />
<Button
android:id="#+id/photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Capture Image"
android:textSize="26sp" />
<Button
android:id="#+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Upload Photo"
android:textSize="26sp" />
</LinearLayout>
for image uri you should paste your file upload path
I am sending Images and Text to a PHP webservice using the following code.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
entity.addPart("files[]",
new ByteArrayBody(data, "myImage.jpg"));
entity.addPart("message0", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(ImageUpload.this, e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
It works perfectly. But this is only for one image. I want to send 5 images.
Example: Image1 - Text1
Image2 - Text2 etc..
So I am confused about how to store 5 images one by one and then on button click, send these images and text associated with them to the server.
I am getting images from the phone's camera.
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
public void onActivityResult_photo(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {
if (data != null) {
mImageCaptureUri = data.getData();
display(mImageCaptureUri);
} else {
Toast.makeText(CustomTabActivity.mTabHost.getContext(),
"No photo selected..", Toast.LENGTH_SHORT).show();
}
}
}
private String display(Uri mImageCaptureUri2) {
// TODO Auto-generated method stub
String base64string = null;
try {
if (mImageCaptureUri2 != null) {
System.gc();
selectedImagePath = getPath(mImageCaptureUri2);
File filenew = new File(selectedImagePath);
int file_size = Integer.parseInt(String.valueOf(filenew
.length() / 1024));
if (file_size <= 10000) {
PD1 = ProgressDialog.show(
CustomTabActivity.mTabHost.getContext(), "",
"Loading...");
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
PD1.setCancelable(true);
Bitmap newbitmap;
newbitmap = decodeFile(selectedImagePath);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
newbitmap.compress(Bitmap.CompressFormat.PNG, 50,
bs);
img.setVisibility(View.VISIBLE);
img.setImageBitmap(newbitmap);
byte[] abc = bitmapToByteArray(newbitmap);
if (txt_phototext.getText().toString().equals("")) {
submit.put(abc, "");
} else {
submit.put(abc, txt_phototext.getText()
.toString());
// executeMultipartPost();
}
PD1.dismiss();
}
});
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
CustomTabActivity.mTabHost.getContext());
alertbox.setMessage("Take Image Size Less than 10 MB");
alertbox.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
finish();
}
});
alertbox.show();
}
} else {
System.out.println("===============NULL========");
}
} catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
}
return base64string;
}
static Bitmap decodeFile(String str) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(str), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(str), null,
o2);
} catch (FileNotFoundException e) {
}
return null;
}
public static byte[] bitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
return bitmapdata;
}
And make sure that your directory or folder in server is Executable, Writable and Readable. I had this as the major problem. This is called 777 permission.. Believe me, this is as important as other things to consider.
For full detail please have a look on my post Click here
its quite difficult to send multiple images to server using MultipartEntity. I did search for this but didn't find any right solution then i made my own way to send multiple images to server
, here i send array of selected paths to asynctask and in asynctask i sent images to server
Calling Asysnctask Function-
new Upload_Multiple.excute(Array_of_Path[]))
Private class Upload_Multiple_img extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
protected String doInBackground(String... paths_array) {
String data = "";
for (int i = 0; i < paths_array.length; i++) {
// get_Picture_bitmap() returns bitmap by passing path of image
// get_Picture_bitmap() is mentioned below.
Bitmap bitmap = get_Picture_bitmap(paths_array[i]);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert
DefaultHttpClient httpclient = new DefaultHttpClient();
String server_funtion_url="...serveraddres"+funtion_at_server"";
HttpPost httppost = new HttpPost(server_funtion_url); // server
MultipartEntity reqEntity = new MultipartEntity();
obj_SP = ImagePicker.this.getSharedPreferences("Eperty", 0);
String id_prop = obj_SP.getString("new_prop_id", "");
String Image_Name =
+ String.valueOf(System.currentTimeMillis()) + ".jpg";
// image is a key which is used at server end to get this
reqEntity.addPart("image", Image_Name, in);
httppost.setEntity(reqEntity);
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
data = EntityUtils.toString(response.getEntity());
System.out.println("FFFF== " + data);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return data;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
ConstantData.ToastAlert(ImagePicker.this,
"Images Uploaded successfully");
}
}
//);
For compressing the images and getting bitmap for i made below funtion*
public Bitmap get_Picture_bitmap(String imagePath) {
long size_file = getFileSize(new File(imagePath));
size_file = (size_file) / 1000;// in Kb now
int ample_size = 1;
if (size_file <= 250) {
System.out.println("SSSSS1111= " + size_file);
ample_size = 2;
} else if (size_file > 251 && size_file < 1500) {
System.out.println("SSSSS2222= " + size_file);
ample_size = 4;
} else if (size_file >= 1500 && size_file < 3000) {
System.out.println("SSSSS3333= " + size_file);
ample_size = 8;
} else if (size_file >= 3000 && size_file <= 4500) {
System.out.println("SSSSS4444= " + size_file);
ample_size = 12;
} else if (size_file >= 4500) {
System.out.println("SSSSS4444= " + size_file);
ample_size = 16;
}
Bitmap bitmap = null;
BitmapFactory.Options bitoption = new BitmapFactory.Options();
bitoption.inSampleSize = ample_size;
Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption);
ExifInterface exif = null;
try {
exif = new ExifInterface(imagePath);
} catch (IOException e) {
// Auto-generated catch block
e.printStackTrace();
}
int orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix matrix = new Matrix();
if ((orientation == 3)) {
matrix.postRotate(180);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else if (orientation == 6) {
matrix.postRotate(90);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else if (orientation == 8) {
matrix.postRotate(270);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else {
matrix.postRotate(0);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
}
return bitmap;
}
**
Server end Code *
$target_dir = "../webadmin/user_image/";
$target_dir = $target_dir . basename($_FILES["user_img"]["name"]);
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir))
{
$msg = "The file ". basename($result[0]). " has been uploaded.";
$send_arr['success'] = 1;
$send_arr['message'] = $msg;
echo json_encode($send_arr);
}
else
{
$msg = "Sorry, there was an error uploading your file.";
$send_arr['success'] = 0;
$send_arr['message'] = $msg;
echo json_encode($send_arr);
}
Why you can't just create array of json object of your images to base64 and post to server and at your server api read those images convert to byte and use as image.
Check my answe and try to implement.
In Android how to post data to webservice which is created in WCF?
And the images you are getting from camera store them in uri in sdcard and letter read them. You can assign image name sequntialy. And read them from uri.
Try increasing the post_max_size of your php.ini file in WAMP server
Please find the below method...here i m sending mutiple image file using AQUERY. The best lib to perform all background network related task.(Like AJAX).
https://code.google.com/p/android-query/
public void uploadImageFile( String filePath,
String message) {
Context context = ApplicationContextProvider.getContext();
String url = SERVER_URL + "/user/uploadImageFile";
try {
Toast.makeText(context, "Uploading...", Toast.LENGTH_SHORT)
.show();
String compressedFile = CommonUtilities.compressImage(filePath,
context);
Map<String, Object> params = new HashMap<String, Object>();
File imageFile = new File(compressedFile);
byte[] imageBytes1 = FileUtils.readFileToByteArray(imageFile);
params.put("imageBytes", imageBytes1);
params.put("message",URLEncoder.encode(message, "UTF-8"));
AQuery aq = new AQuery(context);
aq.ajax(url, params, JSONObject.class,
new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json,
AjaxStatus status) {
Toast.makeText(
ApplicationContextProvider.getContext(),
"Uploaded successfully",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
I use the following codes to launch the camera from my app:
private void saveFullImage() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName()
+ File.separatorChar + "Android/data/"
+ RegistrationDetails.this.getPackageName() + "/files/"
+ md5("filedummy") + ".jpg";
File photoFile = new File(path);
try {
if (photoFile.exists() == false) {
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
Uri fileUri = Uri.fromFile(photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState).setCancelable(true)
.create().show();
}
}
And I have the following codes in onActivityResult to show that the picture has been taken, so I can proceed the next step:
} else if (requestCode == TAKE_PICTURE) {
if (data == null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Take Picture finished", 10);
toast.show();
}
And I have defined the following settings in AndroidManifest: android.permission.CAMERA and android.permission.WRITE_EXTERNAL_STORAGE
The launch Camera intent works, but when I make a picture and click on Save, then it does not return to onActivityResult and my app crashes.
Can someone help me with this?
Thanks
I got some problems with Galaxy S version 2.3.4 and camera.
After a little work, it actually work with this code (tested with Galaxy S and Nexus S).
You can try it and say me if it works for you.
private Uri mCapturedImageURI;
private void takePhoto() {
String fileName = "temp.jpg";
if (isGalaxyS()) {
fileName = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
File fileTmp = new File(fileName);
if (fileTmp.exists()) fileTmp.delete();
mCapturedImageURI = Uri.fromFile(fileTmp);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image prise via XXX :)");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
private boolean isGalaxyS() {
Log.d("Photo", android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
ArrayList<String> devices = new ArrayList<String>();
devices.add("samsung/GT-I9000/GT-I9000");
return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA: {
Bitmap photo = null;
String filenameDest = Repertoires_S.getInstance().Get_Photos_Path() + DateTime_BO_S.getInstance().Date_Courante_AAAAMMJJ_HHMMSS() + ".jpg";
File fDest = new File(filenameDest);
String capturedImageFilePath;
if (data == null) {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" utilisé
try {
if (isGalaxyS()) {
String fileName = "temp.jpg";
capturedImageFilePath = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
} else {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
capturedImageFilePath = cursor.getString(column_index_data);
}
File fSrc = new File(capturedImageFilePath);
fSrc.renameTo(fDest);
photo = BitmapFactory.decodeFile(filenameDest);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" non utilisé -> miniature
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
}
}
if (photo != null) {
try {
int tailleMaxPhoto = 800;
double rap;
int newWidth;
int newHeight;
if (photo.getWidth() > tailleMaxPhoto || photo.getHeight() > tailleMaxPhoto) {
// Si c'est plus grand on redimensionne
if (photo.getWidth() > photo.getHeight()) {
rap = (double)tailleMaxPhoto / photo.getWidth();
newWidth = tailleMaxPhoto;
newHeight = (int)((double)photo.getHeight() * rap);
} else {
rap = (double)tailleMaxPhoto / photo.getHeight();
newHeight = tailleMaxPhoto;
newWidth = (int)((double)photo.getWidth() * rap);
}
Bitmap photoSmall = Bitmap.createScaledBitmap(photo, newWidth, newHeight, true);
if (photoSmall != null) {
FileOutputStream out = new FileOutputStream(filenameDest);
if (photoSmall.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
}
} else {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
}