POST base64 image using okHTTP, not getting any result - android

Edit: Ok, this is my last attempt at this, new code same result. I get a image in the ImageView but no sign of any return-string from the server.
This is what the server expects to get (The image can be url or base64 encoded image):
POST /detect HTTP/1.1
Content-Type: application/json
app_id: 4985f625
app_key: aa9e5d2ec3b00306b2d9588c3a25d68e
{
"image":" http://media.kairos.com/kairos-elizabeth.jpg ",
"selector":"ROLL"
}
And this is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
EncodeToBase64 encode = new EncodeToBase64();
String lastPhotoAsBase64;
ImageView mImageView;
String path = Environment.getExternalStorageDirectory().toString() + "/files/Pictures";
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
String mTestPath = "/storage/emulated/0/Android/data/com.example.cliff.camera2/files/Pictures/JPEG_20171209_174301_1623885500.jpg";
String jsonResult;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
Button cameraButton = findViewById(R.id.cameraButton);
textView = findViewById(R.id.textView);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
try {
setPic();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
public void setPic() throws IOException {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
//BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
ExifInterface exif = new ExifInterface(mCurrentPhotoPath);
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
//int deg = rotationInDegrees;
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
lastPhotoAsBase64 = encode.encode(bitmap);
if(lastPhotoAsBase64 != null) {
new postData().execute(lastPhotoAsBase64);
}
else{
Toast.makeText(MainActivity.this,"No base64 data found!",Toast.LENGTH_LONG).show();
}
mImageView.setImageBitmap(bitmap);
}
public void dispatchTakePictureIntent() {
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();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
public class postData extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
HttpConnectionActivity hh = new HttpConnectionActivity();
String temp = hh.HttpConnection(strings[0]);
textView.setText(temp);
textView.setVisibility(View.VISIBLE);
return null;
}
}
}
HttpConnectionActivity.java
public class HttpConnectionActivity {
private final static String KAIROS_URL = "https://api.kairos.com/detect";
private final String KEY = "5232cdde7e35d8de7ac78726060d5a01";
private final String ID = "9bd755a1";
String serverResponse;
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
JSONObject postdata = new JSONObject();
public String HttpConnection(String image) {
OkHttpClient client = new OkHttpClient();
try {
postdata.put("image", image);
RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());
final Request request = new Request.Builder()
.url(KAIROS_URL)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("app_id", ID)
.addHeader("app_key", KEY)
.build();
Response response = client.newCall(request).execute();
serverResponse = response.body().string();
} catch (Exception ex) {
ex.getMessage();
}
return serverResponse;
}
}
EncodeToBase64.java
public class EncodeToBase64 {
public String encode(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
}
OnCustomEventListener.java
public interface OnCustomEventListener {
public void onEvent();
}

Related

how can i compress image size before uploading this is my code

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.

Issue with AirLocation library

I have a project and i am using airlocation library for one activity to fetch the location. App is working fine at my end but the playstore reports show some frequent crashes and i am trying to debug it.
Here is my activity code
public class Selfie extends AppCompatActivity {
private AirLocation airLocation;
public static final String TAG = "SelfieAct";
private static final int REQUEST = 1856;
private TextView Time, location;
Button time_stamp, lcn_btn, Atten_btn;
private static final String TIME_STAMP = null;
NetworkController networkController;
private Button cptrm_btn;
private ImageView imgview;
private static final int CAMERA_REQUEST = 1888;
SharedPreferences prefs;
Gson gson = new Gson();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
private SharedPreferences.Editor editor;
CheckBox checkBox;
Bitmap lesimg;
private LocationManager locationManager;
private String locationText;
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
File photoFile;
boolean facelocationset = false;
TextView textView;
Uri photoUri;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selfie_activity);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
swipeRefreshLayout = findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
networkController = RetrofitClientInstance.getRetrofitInstance().create(NetworkController.class);if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
if (!hasPermissions(Selfie.this, PERMISSIONS)) {
Toast.makeText(this, "Please allow location permission", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(Selfie.this, PERMISSIONS, REQUEST );
} else {
//do here
}
} else {
//do here
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Toast.makeText(this, "Cannot Continue Without Location Permission", Toast.LENGTH_SHORT).show();
finish();
return;
}
Time = findViewById(R.id.time);
prefs = getSharedPreferences(getResources().getString(R.string.prefs), MODE_PRIVATE);
editor = getSharedPreferences(getResources().getString(R.string.prefs), MODE_PRIVATE).edit();
Atten_btn = findViewById(R.id.mark_Attendence);
cptrm_btn = findViewById(R.id.cptr_btn);
imgview = findViewById(R.id.imageView10);
textView=findViewById(R.id.Waitmsg);
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationText = addresses.get(0).getAddressLine(0);
textView.setText(locationText);
facelocationset = true;
}
#Override
public void onFailed(#NotNull AirLocation.LocationFailedEnum locationFailedEnum) {
// do something
}
});
cptrm_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cameraIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
ex.printStackTrace();
Log.d(TAG, "onClick: " + ex.getMessage());
Log.d(TAG, "onClick: " + ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoUri = FileProvider.getUriForFile(Selfie.this, BuildConfig.APPLICATION_ID + ".provider", photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
});
Atten_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(facelocationset && mImageBitmap != null) {
Date dt = new Date(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
RequestBody requestFile = RequestBody.create(
MediaType.parse(getContentResolver().getType(FileProvider.getUriForFile(Selfie.this, BuildConfig.APPLICATION_ID + ".provider", photoFile))),
photoFile
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", photoFile.getName(), requestFile);
MultipartBody.Part io_time =
MultipartBody.Part.createFormData("io_time", df.format(dt));
MultipartBody.Part user_id =
MultipartBody.Part.createFormData("user_id", prefs.getString("uid", null));
MultipartBody.Part loc =
MultipartBody.Part.createFormData("loc", locationText);
RequestBody enctype = RequestBody.create(
okhttp3.MultipartBody.FORM, "multipart/form-data");
networkController.mark_attendance("Bearer " + prefs.getString("token", null), enctype, body, io_time, user_id, loc).enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.code() == 200) {
if(response.body().get("ok").getAsString().equals("true")){
Log.d(TAG, "onResponse: " + "Done");
Toast.makeText(Selfie.this, "Punch Success", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d(TAG, "onFailure: "+ Log.getStackTraceString(t));
}
});
}
else{
Toast.makeText(Selfie.this, "Waiting for Location or Image" , Toast.LENGTH_SHORT).show();
}
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
airLocation.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
InputStream ims = getContentResolver().openInputStream(photoUri);
mImageBitmap = BitmapFactory.decodeStream(ims);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Bitmap mImageDisplayBitmap = handleSamplingAndRotationBitmap(getApplicationContext(), photoUri);
imgview.setImageBitmap(mImageDisplayBitmap);
}
catch (IOException io){}
File file = new File (String.valueOf(photoFile));
try {
mImageBitmap = new Compressor(this)
.setMaxHeight(200) //Set height and width
.setMaxWidth(200)
.setQuality(100) // Set Quality
.compressToBitmap(photoFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream fOut = new FileOutputStream(file);
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
}
catch(FileNotFoundException f){}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
airLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do here
} else {
Toast.makeText(Selfie.this, "The app was not allowed to read your store.", Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(context, img, selectedImage);
return img;
}
private static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
}
The playstore reports show NullPointerException in this block of code
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
locationText = addresses.get(0).getAddressLine(0);
textView.setText(locationText);
facelocationset = true;
}
Can anyone please find out which line of code can be the cause this issue and how do i resolve it.
airLocation = new AirLocation(this, true, true, new AirLocation.Callbacks() {
#Override
public void onSuccess(#NotNull Location location) {
Geocoder geocoder = new Geocoder(Selfie.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
}
// ***** Changes *****
if (addresses != null) {
locationText = addresses.get(0).getAddressLine(0);
if (locationText != null) {
textView.setText(locationText);
}
facelocationset = true;
}
}
}

Tesseract based OCR app shows failed to read bitmap error

I am developing an Android Application in which i would like to capture a image and extract text from that .I used tessaract library. I put a image in drawable folder and checked it works fine but when it comes to scanning a captured image an application closing.Here is my code
public class MainActivity extends AppCompatActivity {
EditText editText;
ImageView imageView;
Uri outuri;
File imgdir;
private static final int CAMERA_REQUEST = 1888;
Bitmap bitmap;
File imagename;
private TessBaseAPI vinodtessbaseapi;
// String lang = "eng";
String path;
File DATA_PATH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
imageView = (ImageView) findViewById(R.id.imageView);
path = Environment.getExternalStorageDirectory().toString()+"/VinodOCR";
// path = getFilesDir()+"/VinodOCR/tessdata";
checkFile(new File(path+"tessdata/"));
String lang = "eng";
vinodtessbaseapi = new TessBaseAPI();
vinodtessbaseapi.init(path,lang);
}
public void imageok(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imgdir = new File(Environment.getExternalStorageDirectory().toString(), "VinodOCR/imgs");
imgdir.mkdirs();
imagename = new File(imgdir, "Vinod_" + timestamp + ".jpg");
outuri = Uri.fromFile(imagename);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
startActivityForResult(intent, 1);
Toast.makeText(this, "Image saved in directory", Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/VinodOCR/imgs"+imagename, options);
try {
ExifInterface exif = new ExifInterface(String.valueOf(Environment.getExternalStorageDirectory()+"/VinodOCR/imgs"+imagename));
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Toast.makeText(this, "Orient", Toast.LENGTH_LONG).show();
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
// Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Toast.makeText(this, "Couldn't correct orientation:" + e.toString(), Toast.LENGTH_LONG).show();
}
}
private void checkFile(File dir){
if(!dir.exists()&&dir.mkdirs()){
copyFile();
}
if(dir.exists()){
String dfpath = DATA_PATH+"/tessdata/eng.traineddata";
File datafile = new File(dfpath);
if(!datafile.exists()){
copyFile();
}
}
}
private void copyFile(){
try {
String filepath = DATA_PATH+"/tessdata/eng.traineddata";
AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open("tessdata/eng.traineddata");
OutputStream outputStream = new FileOutputStream(filepath);
byte[] buffer = new byte[1024];
int reads;
while ((reads = inputStream.read(buffer))!= -1){
outputStream.write(buffer,0,reads);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void processImage(View view){
vinodtessbaseapi.setImage(bitmap);
String OCRResult = vinodtessbaseapi.getUTF8Text();
// TextView ocrtextview = (TextView)findViewById(R.id.OCRTextView);
editText.setText(OCRResult);
}
}
I am attaching the error log also. Kindly please help me to get rid of this error:

Json parsing with AQuery library of android

Is there any solution to use AQuery library of android for JSON parsing? Do give the code for it. Any solution that makes use of AQuery and no need to create JSONObject instance and to get object from there. Any direct solution for it, please do answer it with a sample of code.
-- Complete code for capturing image ,saving to SD card , pick from gallery,compress,rotate image,etc.. 200% working.
public class A extends AppCompatActivity implements View.OnClickListener, AsyncTaskCompleteListener {
private static final String IMAGE_DIRECTORY = "/idyme";
private static int MAX_IMAGE_DIMENSION = 200;
private final String TAG = "RegisterFragment";
private Button btnVerify, btnUploadImage;
private String ImgPath = null, filePath = null,
profileImageFilePath, profileImageData = null,imageVideoType = "", imageVideoPath = "";
private ImageView ivImage;
private AQuery aQuery;
private Uri uri = null;
private ImageOptions imageOptions;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vip_registration);
ivImage = (ImageView) findViewById(R.id.ivProfile);
aQuery = new AQuery(this);
imageOptions = new ImageOptions();
imageOptions.memCache = true;
imageOptions.fileCache = true;
imageOptions.fallback = R.drawable.userimage;
}
#Override
public void onClick(View v) {
// onRegisterButtonClick();
switch (v.getId()) {
case R.id.btnUploadImage:
showPictureDialog();
}
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle(getResources().getString(
R.string.dialog_chhose_photo));
String[] pictureDialogItems = {
getResources().getString(R.string.dialog_from_gallery),
getResources().getString(R.string.dialog_from_camera)};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, Constants.CHOOSE_PHOTO);
}
private void takePhotoFromCamera() {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(),
(cal.getTimeInMillis() + ".jpg"));
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// uri = Uri.fromFile(file);
uri = getOutputMediaFileUri();
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cameraIntent, Constants.TAKE_PHOTO);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private String getRealPathFromURI(Uri contentURI) {
String result;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(contentURI, proj, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file
// path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == Constants.CHOOSE_PHOTO) {
if (data != null) {
Uri contentURI = data.getData();
profileImageData = getRealPathFromURI(contentURI);
// new AQuery(getApplicationContext()).id(ivMeme).image(
// profileImageData, imageOptions);
try {
String path = saveImage(scaleImage(this, contentURI));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} catch (IOException e) {
e.printStackTrace();
Utils.showToast("Failed", this);
}
}
} else if (requestCode == Constants.TAKE_PHOTO) {
// old
if (uri != null) {
profileImageFilePath = uri.getPath();
if (profileImageFilePath != null
&& profileImageFilePath.length() > 0) {
File myFile = new File(profileImageFilePath);
String path = saveImage(BitmapFactory
.decodeFile(profileImageFilePath));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} else {
Utils.showToast("Failed", this);
}
} else {
Utils.showToast("Failed", this);
}
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
AppLog.Log("TAG", "File Saved::-> " + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY, "Oops! Failed create " + IMAGE_DIRECTORY
+ " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
return mediaFile;
}
public static Bitmap scaleImage(Context context, Uri photoUri)
throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION
|| rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth)
/ ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight)
/ ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
}
--After getting images send it to server , like this :
map.put(Constants.Params.PROFILEPICTURE, imageVideoPath);
// Log.d("image view", profileImageFilePath);
new MultiPartRequester(this, map,
AndyConstants.ServiceCode.VIP_USER_REGISTRATION, this);
-- Permission required :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
-- dependencies :
compile files('libs/android-query-full.0.26.7.jar')
-- this is full code for json parsing with AQuery library of android

Android - Take a picture from the Camera and save it to the internal storage

I have been stuck on this problem for a while now.
I am trying to take a picture with the Camera and save the full size picture directly into the internal memory.
I can save to the external storage without a glitch, but for some reason I cannot get it to work for the internal memory.
The solution below ONLY saves the small picture returned by the data object, and not the full-size picture.
It seems that the camera does not retrieve the full size picture, or that when I use file functions (new File, FileOutputStream...), Android is not retrieving the image from the camera Intent (shows a blank image).
I read all the forums, tutorials and tried different ways of achieving this, but I have not found the answer. I can't be the only one trying to do this.
Could you please help me with this problem?
Thanks!
Here is my code:
public class AddItem extends Fragment {
ListCell cell = new ListCell();
View view;
private Bitmap mImageBitmap;
protected myCamera cameraObject = null;
private Button saveBtn;
private Button cancelBtn;
DBSchema dbSchema;
protected boolean bdisplaymessage;
protected boolean ExternalStorage = false;
public AddItem(){
}
private class ListCell{
private EditText total;
private ImageView mImageView;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.add_item, container,
false);
saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);
cameraObject = new myCamera();
cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
cell.mImageView.setImageResource(R.drawable.camera_icon);
cell.mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//save item to internal db
//get names of columns from db
bdisplaymessage = true;
dbSchema = new DBSchema();
Transaction transac = dbSchema.new Transaction();
Context context = getActivity().getApplicationContext();
//put values in content values
ContentValues values = new ContentValues();
values.put(transac.Total,cell.total.getText().toString());
StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
long nInsert = 0;
nInsert = statusData.insert(values,dbSchema.table_transaction);
if(nInsert!=0){
Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
}
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//redirect to home page
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
}
});
return rootView;
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
//take picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String mCurrentPhotoPath;
File f = null;
try {
//create image
f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());
cameraObject.setCurrentPath(f.getAbsolutePath());
Log.d("uri_fromfile",Uri.fromFile(f).toString());
//uncomment the line below when ExternalStorage=true
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestcode, int resultCode, Intent data) {
if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
handleCameraPhoto(data);
}
}
private void handleCameraPhoto(Intent data) {
setPic(data);
galleryAddPic();
}
private void setPic(Intent data) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = cell.mImageView.getWidth();
int targetH = cell.mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
Log.d("image_path",cameraObject.getCurrentPath());
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = null;
if(ExternalStorage){
bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
}
else{
File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
String picturePath = reportFilePath.toString();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(reportFilePath);
bitmap = (Bitmap) data.getExtras().get("data");
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
fos.close();
}
catch (Exception ex) {
Log.i("DATABASE", "Problem updating picture", ex);
picturePath = "";
}
/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
//File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
//bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
//FileOutputStream fos = null;
//try {
//fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use the compress method on the BitMap object to write image to the OutputStream
//fos.close();
//Bitmap bitmap = null;
/*try{
FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
bitmap = BitmapFactory.decodeStream(fis);
//
fis.close();
}
catch(Exception e){
Log.d("what?",e.getMessage());
bitmap = null;
}*/
/*} catch (Exception e) {
e.printStackTrace();
}*/
/*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
//bitmap = (Bitmap) data.getExtras().get("data");
}
/* Associate the Bitmap to the ImageView */
cell.mImageView.setImageBitmap(bitmap);
cell.mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(cameraObject.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
My other class called myCamera handles the camera:
public class myCamera extends MainMenu{
private ImageView mImageView;
private Bitmap mImageBitmap;
static final String BITMAP_STORAGE_KEY = "viewbitmap";
static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final int ACTION_TAKE_PHOTO_B = 1;
protected static final int ACTION_TAKE_PHOTO_S = 2;
protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
protected Uri fileUri;
protected String mCurrentPhotoPath;
protected static final String JPEG_FILE_PREFIX = "IMG_";
protected static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
protected String mAlbumName;
protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;
protected String getAlbumName() {
return "test";
}
protected String getCurrentPath(){
return mCurrentPhotoPath;
}
protected void setCurrentPath(String mCurrentPhotoPath){
this.mCurrentPhotoPath=mCurrentPhotoPath;
}
public File getAlbumStorageDir(String albumName) {
return new File (
Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ albumName
);
}
private File getAlbumDir() {
File storageDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.base_for_drawer);
mAlbumName = getIntent().getStringExtra("AlbumName");
}
public myCamera(){
}
//save full size picture
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
return image;
}
protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {
mAlbumName = albumName;
File f =null;
if(ExternalStorage){
f = createImageFile();
}
else{
f = saveToInternalSorage(context);
}
// Save a file: path for use with ACTION_VIEW intents
if(f !=null){
mCurrentPhotoPath = f.getAbsolutePath();
}
return f;
}
private File saveToInternalSorage(Context context) throws IOException{
ContextWrapper cw = new ContextWrapper(context);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + "hello";
// path to /data/data/yourapp/app_data/imageDir
File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);
/*below is a bunch of options that I tried*/
//File directory =context.getFilesDir();
//File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);
// Create imageDir
//File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
//File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
//return image;
return mypath;
}
}
I found the solution! I did not use the native camera application, but rather created my own camera class and use the data sent back by the camera via a callback. Works smoothly!

Categories

Resources