Grayscaling doesn't affect my image - java

I am using tessaract to scan text and convert it into a string , so far so good , but i have a problem with grayscaling an image. I have images captured with my camera and I want to grayscale them and to rescale them in order to save some memory , i did this by using the BitmapFactory.Options and the method inSimpleSize(put it in 4).
After that i've tried to get the image from the folder that it is and grayscale it. But didn't work - the text can't be extracted from the photo. However when i removed grayscaling worked.
Here is my code :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imgUri.getPath() , options);
// bitmap = toGrayscale(bitmap);
result = extractText(bitmap);
textView.setText(result);
The extractText method simply calls Tessaract and scan the image and it's working fine without the grayscaling.
My toGrayscale code which i found online ( it is working , i have tried it as a filter and i was happy with it) :
public Bitmap toGrayscale(Bitmap bmpOriginal)
{
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
Here is my code for capturing photos with the camera :
if (captureImg != null) {
captureImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCameraActivity();
}
});
private void startCameraActivity() {
try {
String IMGS_PATH = Environment.getExternalStorageDirectory().toString() + "/Noetic/imgs";
prepareDirectory(IMGS_PATH);
String img_path = IMGS_PATH + "/ocr.jpg";
outputFileUri = Uri.fromFile(new File(img_path));
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, PHOTO_REQUEST_CODE);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
I was looking for a solution but didn't find anything. I have some theories why this doesn't work - one of them is because my grayscaling method creates the same image but new (so BitmapFactory.Options.getSampleSize becomes useless). Any help will be much appriciated.
Thanks in advance!

Try to use Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); instead of Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

Related

OpenCV-Android java.lang.IllegalArgumentException: bmp == null error

I got this error.
java.lang.IllegalArgumentException: bmp == null
I referred this link
OpenCV - Android : java.lang.IllegalArgumentException: bmp == null
So I made code like this.
inputBitmap.createBitmap(matInput.cols(), matInput.rows(),
Bitmap.Config.ARGB_8888);
And this is my code related to Bitmap
private ImageView imageView_matInput;
private ImageView imageView_matResult;
private Mat matInput;
private Mat image_matches;
Bitmap myBitmap = null;
Bitmap inputBitmap = null;
Bitmap resultBitmap = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
matInput = new Mat();
image_matches = new Mat();
imageView_matInput = (ImageView)findViewById(R.id.imageView_matInput);
imageView_matResult = (ImageView)findViewById(R.id.imageView_matResult);
File imageFile = new File(Global.imageFileName);
if(imageFile.exists()) {
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
Log.d(TAG, imageFile.getAbsolutePath());
}
processingImage();
}
public void processingImage() {
Utils.bitmapToMat(myBitmap, matInput);
Imgproc.cvtColor(matInput, matInput, Imgproc.COLOR_RGB2GRAY);
surfWithFlann4(matInput.getNativeObjAddr(), image_matches.getNativeObjAddr());
Imgproc.resize(image_matches, image_matches, matInput.size());
inputBitmap.createBitmap(matInput.cols(), matInput.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(matInput, inputBitmap);
resultBitmap.createBitmap(image_matches.cols(), image_matches.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(image_matches, resultBitmap);
imageView_matInput.setImageBitmap(inputBitmap);
imageView_matResult.setImageBitmap(resultBitmap);
}
Global is a Class that has a path of a image taken by camera.
matInput is not null and surfWithFlann4 is a native function that compares a picture taken by camera to images from asset directory.
The java.lang.IllegalArgumentException: bmp == null error occured in here
Utils.matToBitmap(matInput, inputBitmap);

How to resize image that captured from camera and display on imageview

now i develop an android app that need to upload image to my server. but when i try load image to imageview it just show blank. when i change the resolution from 1300 pixels to 300 pixels then the image can display at ImageView. my Code i like below. Please help
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
viewImage = (ImageView)findViewById(R.id.imgInv);
int width = viewImage.getWidth();
int height = viewImage.getHeight();
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOptions.inDither = true;
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
viewImage.setImageBitmap(bitmap);
OutputStream outFile = null;
File file = new File(path,String.valueOf(System.currentTimeMillis()) + ".jpg");
imgName = mName + "_" + String.valueOf(System.currentTimeMillis());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] b = baos.toByteArray();
imgData = Base64.encodeToString(b,Base64.DEFAULT);
}
}
I'm not talking about your code but there is a library for what you want. You can use Picasso library that has complete features for working on images like as downloading, caching etc.
You can get it from here with an example.
Also there is a tutorial about it

Getting bitmap image from camera intent as thumbnail.How to make it bigger

I am trying to open my camera app and get the image onto an imageview.Even when i use wrap content for the imageview's width and height, it is shown as a thumbnail.I have seen several posts for resizing it and am not sure which one to use.The issue is that i want the image as it is , that is in its full size, not as a thumbnail.The following is what i have tried:
inside a button click event:
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 111);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK && requestCode == 111) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
preview.setImageBitmap(photo);
}
I am trying to show the image as a preview inside an imageview.The issue is i want a bigger image.When i try changing the widht and height of the imageview to 300px and 150px , i get a blank.
How do i get a bigger image?
EDIT:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
In on activity result:
if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE)
{
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
preview.setImageBitmap(bitmap);
}
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)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
But still i get the same size.
You have to supply the Intent with a putExtra option and a filename for where to store it. The extra data is just a snapshot.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath)));
It'll save the image to the specified location (as long as it's writable and such)

android_Get pictures from SDcard

Get pictures ​​path from SDcard.
My picture name is 01.jpg.
Make sure the picture is inside the SD card.
public boolean fileIsExists(){
try{
File f1 = new File("/sdcard/01.jpg");
f1 = new File("01.jpg");
if(!f1.exists()){
return true;
}
}catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
boolean file1 = fileIsExists();
If picture is inside the SD card,then put picture into imageview.
Error is in the following code
if (file1==true){
imageView = (ImageView)findViewById(R.id.image_view);
String myJpgPath = "/sdcard/01.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bitmap = BitmapFactory.decodeFile(myJpgPath, options);//error here Cellphone can't run
imageView.setImageBitmap(bitmap);
}
Just try Following Code.
File f = new File("/mnt/sdcard/01.jpg");
ImageView mImgView1 = (ImageView)findViewById(R.id.imageView);
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
mImgView1.setImageBitmap(bmp);
set your path like this:
String myJpgPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"folderName/01.jpg";
Change +"sdcard/01.jpg"; to +"/01.jpg";
(And make sure Bitmap bitmap isn't repeat the local variables.)
if (file1==true){
String myJpgPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/01.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bitmap = BitmapFactory.decodeFile(myJpgPath, options);
imageView.setImageBitmap(bitmap);
}

Images selected with gallery are MUCH bigger then when taken with camera

in my app a user either picks an image from their image gallery or captures an image with their camera.
When you capture it is added to the gallery of the user.
I have found that the images, besides being the same image have massive changes in size.
Captured: 33kb
CODE:
if (requestCode == TAKEIMAGE) {
System.out.println("TAKE IMAGE");
int photoLength = 0;
Bitmap photo = (Bitmap) data.getExtras().get("data");
photoLength = GetBitmapLength(photo);
SetSubmissionImage(photo, photoLength);
}
Taken from gallery: 1600kb
CODE:
else if (requestCode == CHOOSEIMAGE) {
System.out.println("CHOOSE IMAGE");
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
int photoLength = 0;
Bitmap photo = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
bMapArray = null;
fileis.close();
bufferedstream.close();
//rotate to be portrait properly
try {
ExifInterface exif = new ExifInterface(selectedImagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
}
else if (orientation == 3) {
matrix.postRotate(180);
}
else if (orientation == 8) {
matrix.postRotate(270);
}
photo = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); // rotating bitmap
}
catch (Exception e) {
}
//photo = GetCompressedBitmap(photo);
photoLength = GetBitmapLength(photo);
SetSubmissionImage(photo, photoLength);
}
Like other said in comments you need to start the camera activity with an intent that contains an uri where image will be saved:
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Then in your onActivityResult() method you can retrive the uri and load the image the from the URI in the intent.

Categories