Compress camera image before upload - android

I am using this code (from www.internetria.com) to take a photo and upload to a server:
onCreate:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri output = Uri.fromFile(new File(foto));
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(intent, TAKE_PICTURE);
onActivityResult:
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageBitmap(BitmapFactory.decodeFile(foto));
File file = new File(foto);
if (file.exists()) {
UploaderFoto nuevaTarea = new UploaderFoto();
nuevaTarea.execute(foto);
}
else
Toast.makeText(getApplicationContext(), "No se ha realizado la foto", Toast.LENGTH_SHORT).show();
UploaderFoto:
ProgressDialog pDialog;
String miFoto = "";
#Override
protected Void doInBackground(String... params) {
miFoto = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://servidor.com/up.php");
File file = new File(miFoto);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody foto = new FileBody(file, "image/jpeg");
mpEntity.addPart("fotoUp", foto);
httppost.setEntity(mpEntity);
httpclient.execute(httppost);
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
And I want to compress the image, because the size is too big.
I don't know how to add bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); to my app

Take a look over here: ByteArrayOutputStream to a FileBody
Something along these lines should work:
replace
File file = new File(miFoto);
ContentBody foto = new FileBody(file, "image/jpeg");
with
Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");
If file size is still an issue you may want to scale the picture in addition to compressing it.

Convert image to Google WebP format it will save you lots of bytes see the following two articles you can also convert webP into JPG/PNG/GIF whatever you want on server side.
Java Wrapper of Google WebP API
How to check out Google WebP library and use it in Android as native library
First, you need to get pixels from Bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
int bytes = bitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
byte[] pixels = buffer.array();
Then, you can get WebP byte array.
int stride = bytes / height;
int quality = 100;
byte[] encoded = libwebp.WebPEncodeRGBA(pixels, width, height, stride, quality);
Test.png (Size: 106KB)
Test.webp(Size: 48KB)

Using okhttp I upload like this:
MediaType MEDIA_TYPE_PNG
= MediaType.parse("image/jpeg");
//Compress Image
Bitmap bmp = BitmapFactory.decodeFile(fileToUpload.getAbsolutePath());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, bos);
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("photo", fileToUpload.getName(), RequestBody.create(MEDIA_TYPE_PNG, bos.toByteArray()))
.build();
request = new Request.Builder()
.url(urlToUploadTo)
.post(requestBody)
.build();
try {
response = client.newCall(request).execute();
if (response != null) {
if (response.isSuccessful()) {
responseResult = response.body().string();
}
}
} catch (IOException e) {
e.printStackTrace();
}

Have a look at the compressImage() method:
public class MainActivity extends Activity {
private Uri fileUri;
private ImageView img_forCompress;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final String IMAGE_DIRECTORY_NAME = "Ibook";
static File mediaFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_forCompress = (ImageView) findViewById(R.id.img_forCompress);
img_forCompress.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent,
CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
});
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
Log.e("path", "media file:-" + mediaFile);
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.e("path", "" + mediaFile.toString());
String filename = mediaFile.toString();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(filename, options);
compressImage(bitmap);
}
private void compressImage(Bitmap photo) {
// TODO Auto-generated method stub
int imageWidth = photo.getWidth();
int imageHeight = photo.getHeight();
long length = mediaFile.length();
int newHeight = 0;
int newWidth = 0;
Toast.makeText(MainActivity.this, "oldwidth="+imageWidth+",oldHeight="+imageHeight,Toast.LENGTH_LONG).show();
Log.e("Old Image gheight and width---------", imageWidth + "-------"
+ imageHeight + " and Size is -- " + length);
if (imageHeight > 1500 || imageWidth > 1500) {
if (imageHeight > imageWidth) {
Log.e("height is more", "true");
newHeight = 1200;
newWidth = (newHeight * imageWidth / imageHeight);
}
if (imageWidth > imageHeight) {
Log.e("width is more", "true");
newWidth = 1200;
newHeight = (newWidth * imageHeight / imageWidth);
}
}
Toast.makeText(MainActivity.this, "newwidth="+newWidth+",newHeight="+newHeight,Toast.LENGTH_LONG).show();
Log.e("new Image gheight and width---------", newHeight + "-------"

Related

POST base64 image using okHTTP, not getting any result

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

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:

Android File Not Found Exception by saving a foto

I wrote some code to take a picture and save it on external storage. If I run the app, and make the picture I get File Not Found Exception.
Here is my code:
public class CameraActivity extends BaseActivity {
//variables for navigation drawer
private String[] navMenuTitles;
private TypedArray navMenuIcons;
//request code
private static final int ACTIVITY_START_CAMERA_APP = 1777;
//ImageView for the thumbnail
private ImageView mPhotoCapturedImageView;
//File for folder
private File folder;
//variable for timestamp
String timeStamp = "";
//Requestcode for external Storage Permission
final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 42;
//FloatAction Button to save the picture
private FloatingActionButton save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
/*
* Initialize nav draw items
*/
//load title from String.xml
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
//load icons from String.xml
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
//set title and icons
set(navMenuTitles, navMenuIcons);
//initialize ImageView
mPhotoCapturedImageView = (ImageView) findViewById(R.id.imgViewThumbNail);
//creat new intent for the camera app
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//creat and set a timestamp
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//check if permission granted
if (ActivityCompat.checkSelfPermission(CameraActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
if (folder == null) {
createFolder();
}
} else {
ActivityCompat.requestPermissions(CameraActivity.this, new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
}
/*
//create a file with timestamp as title and save it in the folder
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + "MyIdea" + File.separator + "IdeaGallery" + File.separator +
"IMG_" + timeStamp + ".jpg"); */
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(folder));
//start the camera app
startActivityForResult(intent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == ACTIVITY_START_CAMERA_APP)
{
File foto = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Pictures/", "MyIdea/IdeaGalery/" +
"IMG_" + timeStamp + ".jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(foto.getPath(), 1000, 700);
mPhotoCapturedImageView.setImageBitmap(bitmap);
MediaScannerConnection.scanFile(CameraActivity.this, new String[]{foto.getPath()}, new String[]{"image/jpeg"}, null);
//Get our saved file into a bitmap object:
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator + "MyIdea" + File.separator + "IdeaGallery" + File.separator + "IMG_" + timeStamp + ".jpg");
//Bitmap photoCapturedBitmap = BitmapFactory.decodeFile(mImageFileLocation);
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private void createFolder() {
folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/", "MyIdea/IdeaGalery/" +
"IMG_" + timeStamp + ".jpg");
folder.mkdir();
Toast.makeText(getApplicationContext(), "Folder created", Toast.LENGTH_LONG).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length > 0 &&
grantResults [0] == PackageManager.PERMISSION_GRANTED) {
createFolder();
}
}
}
The Permission at Android Manifest were set als
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Can somebody help please help me to find the bug?
I cleaned up my code and i hope you can better understand it. First i check, if folder exist, if not, i create it. Then i create a file for the image. Then I create an Uri from the image and set it to putExtra Method on at the intent.
On activity result, i read the uri from the data and wrap it to a string.
Here is my new code:
//check if imageFolder already exist
if (imageFolder == null) {
//create folder if don't exist
imageFolder = new File(Environment.getExternalStorageDirectory(), "MyIdea/IdeaGallery/");
imageFolder.mkdir();
}
//create imageFile
image = new File(imageFolder, "IMG_" + timeStamp + ".jpg");
//get the uri of the imageFile
Uri uriSavedImage = Uri.fromFile(image);
//put uri path of the image to the intent
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//start the camera app
startActivityForResult(intent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == ACTIVITY_START_CAMERA_APP)
{
if (resultCode == RESULT_OK) {
//Get our saved file into a bitmap object:
Bitmap bitmap = decodeSampledBitmapFromFile(String.valueOf(data.getData()), 1000, 700);
mPhotoCapturedImageView.setImageBitmap(bitmap);
MediaScannerConnection.scanFile(CameraActivity.this, new String[]{image.getPath()},
new String[]{"image/jpeg"}, null);
}
}
}
If i look at the Android Monitor, I cant find the FileNoTFound Exception. But if i check my device, i can't find any folders or images on it.
This messages ist showing on the Android Monitor:
08-22 12:41:08.302 17152-17196/com.example.dudi.myidea I/Adreno-EGL: : QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
08-22 12:41:08.303 17152-17196/com.example.dudi.myidea I/OpenGLRenderer: Initialized EGL, version 1.4
08-22 12:41:08.827 17152-17189/com.example.dudi.myidea W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
08-22 12:41:08.882 17152-17152/com.example.dudi.myidea I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
08-22 12:41:08.906 17152-17196/com.example.dudi.myidea V/RenderScript: 0xa00bc000 Launching thread(s), CPUs 4
Finaly I looked to Android Developer Tutorial and changed my code like the examples in tutorial. Now it works fine. Here my working code:
public class CameraActivity extends BaseActivity {
//variables for navigation drawer
private String[] navMenuTitles;
private TypedArray navMenuIcons;
//request code
private static final int ACTIVITY_START_CAMERA_APP = 1777;
//ImageView for the thumbnail
private ImageView mPhotoCapturedImageView;
//variable for timestamp
//String timeStamp = "";
private static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
//File for folder
//private File imageFolder;
//File for image;
//private File image;
//FloatAction Button to save the picture
private FloatingActionButton save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
/*
* Initialize nav draw items
*/
//load title from String.xml
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
//load icons from String.xml
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
//set title and icons
set(navMenuTitles, navMenuIcons);
//initialize ImageView
mPhotoCapturedImageView = (ImageView) findViewById(R.id.imgViewThumbNail);
//initialize Camera Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//set file uri
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
//put Extra for onActivityResult
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//start camera app
startActivityForResult(intent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours
if (requestCode == ACTIVITY_START_CAMERA_APP)
{
if (resultCode == RESULT_OK) {
//Get our saved file into a bitmap object:
Bitmap bitmap = decodeSampledBitmapFromFile(fileUri.getPath(), 1000, 700);
mPhotoCapturedImageView.setImageBitmap(bitmap);
MediaScannerConnection.scanFile(CameraActivity.this, new String[]{fileUri.getPath()},
new String[]{"image/jpeg"}, null);
} else if (requestCode == RESULT_CANCELED) {
Toast.makeText(this, "Error, user cancelled the image capture", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Imagecapture failed.", Toast.LENGTH_LONG).show();
}
}
}
/* Create a file Uri for saving an image */
private static Uri getOutputMediaFileUri (int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/* Create a file to save an image */
private static File getOutputMediaFile(int type) {
//check if SD-Card is mounted
Boolean isMounted = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
File mediaStorageDir = null;
if (isMounted) {
//create storage directory if does not exist
mediaStorageDir = new File (Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "IdeaGallery");
if (! mediaStorageDir.exists()) {
if (! mediaStorageDir.mkdir()) {
Log.d("IdeaGallery", "failed to create");
return null;
}
}
} else {
Log.d("IdeaGallery", "failed to create");
}
//create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp
+ ".jpg" );
} else {
return null;
}
return mediaFile;
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}

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

why not encode(String) full size image via Base64 in android?

When I want parse full image without resize but must be resize in requirement of code.
When I set
options.inSampleSize = 1;
Then decode of image show black. But I want full image
that means
options.inSampleSize = 1;
and also
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
But I unable to make this.
My code below :
public class MainActivity extends Activity {
public String imageName, imagePath;
public Context context;
public static final String TAG = "MainActivity";
protected static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 0;
public File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + "Test_Folder");
if (dir.exists()) {
Log.i(TAG, "folder already exist");
} else {
if (dir.mkdirs()) {
Log.i(TAG, "folder make now");
}
}
SecureRandom random = new SecureRandom();
String randomName = new BigInteger(10, random).toString(4);
imageName = "myImage" + "" + randomName + ".JPEG";
File file = new File(dir, imageName);
imagePath = file.getAbsolutePath();
Uri outputFileUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(i, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
options.inPurgeable = true;
Bitmap bm = BitmapFactory.decodeFile(imagePath,
options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
// bitmap object
byte[] byteImage_photo = baos.toByteArray();
// generate base64 string of image
String imageRowData = Base64.encodeToString(byteImage_photo,
Base64.DEFAULT);
Log.i(TAG, "::image::" + imageRowData);
}
}
}
}
How to make sure full image encode without resize and decrease quality.
That means I want
options.inSampleSize = 1;
and also
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
It is possible? please help me.

Categories

Resources