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

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

Related

Error when trying to convert ImageView to string

I have a ImageView that I need to create and get the bitmap of and convert to string, because I need to send the image to charquopy for procesisng. When I attempt to get the Image as a string I get the following error below:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
on this line specifically: imageString = getStringImage(bitmap);
the entire code snipped of that related to my problem:
mImageView = (ImageView) findViewById(R.id.frame_image);
#Override
protected void onCreate(final Bundle savedInstanceState) {
String imageString = "";
BitmapDrawable drawable;
Bitmap bitmap;
drawable = (BitmapDrawable)mImageView.getDrawable();
bitmap = drawable.getBitmap();
imageString = getStringImage(bitmap); // Error occurs in this line
}
the frame image XML:
<ImageView
android:id="#+id/frame_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/camera_view"
android:layout_alignLeft="#id/camera_view"
android:layout_alignRight="#id/camera_view"
android:layout_alignTop="#id/camera_view" />
Output:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
I'd like to know why is it returning a null pointer given that Imageview seems to be apparently properly called.
You can draw the imageview on a canvas and create a bitmap out of it like this
ImageView mImageView = (ImageView) findViewById(R.id.frame_image);
Bitmap bitmap = Bitmap.createBitmap(mImageView .getWidth(), mImageView .getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
mImageView.draw(canvas);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String imageAsString =Base64.encodeToString(b, Base64.DEFAULT);
//Upload imageAsString
You can try this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
public class ImageUtil
{
public static Bitmap convert(String base64Str) throws IllegalArgumentException
{
byte[] decodedBytes = Base64.decode(
base64Str.substring(base64Str.indexOf(",") + 1),
Base64.DEFAULT
);
return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
}
public static String convert(Bitmap bitmap)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
}

Custom marker bitmap error Failed to decode image. The provided image must be a Bitmap

I'm using the firebase realtime database to get some users info and show a custom marker for each one.. to set the icon for the marker options I use the method below and it works for most cases.
But more often the app crashes when creating the bitmap of the custom view for the marker..! Is there a way to improve the method and prevent bitmap problems.!
Code
{ // other methods..
private void showMarker() {
BitmapDescriptor pin = BitmapDescriptorFactory
.fromBitmap(getMarkerBitmapFromView(data.getUserAvatar()));
userMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(data.getName() + "")
.snippet(data.getSectionName() + "")
.icon(pin));
}
// I take pic url from firebase and show it into the marker view
private Bitmap getMarkerBitmapFromView(String ImgUrl) {
if (getActivity() != null) {
View customMarkerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.map_marker, null);
CircleImageView markerImageView = customMarkerView.findViewById(R.id.pic_user);
FrameLayout pin = customMarkerView.findViewById(R.id.marker);
pin.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.map_marker_green));
Picasso.with(getActivity())
.load(ImgUrl)
.resize(80, 80)
.error(R.drawable.user_dummy)
.placeholder(R.drawable.user_dummy)
.into(markerImageView);
customMarkerView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache(true);
Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, Mode.SRC_IN);
Drawable drawable = customMarkerView.getBackground();
if (drawable != null) {
drawable.draw(canvas);
}
customMarkerView.draw(canvas);
return returnedBitmap;
} else {
// the crash didn't happen because of this! I've checked using breakpoints, it returns bitmap 99.9% of times.
return null;
}
}
}
The Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.arapeak.katateeb, PID: 30706
com.google.maps.api.android.lib6.common.apiexception.b: Failed to decode image. The provided image must be a Bitmap.
at com.google.maps.api.android.lib6.impl.k.a(:com.google.android.gms.dynamite_dynamitemodulesb#12529020#12.5.29 (040308-192802242):5)
at com.google.maps.api.android.lib6.impl.o.a(:com.google.android.gms.dynamite_dynamitemodulesb#12529020#12.5.29 (040308-192802242):7)
at com.google.maps.api.android.lib6.impl.db.<init>(:com.google.android.gms.dynamite_dynamitemodulesb#12529020#12.5.29 (040308-192802242):25)
at com.google.maps.api.android.lib6.impl.bc.a(:com.google.android.gms.dynamite_dynamitemodulesb#12529020#12.5.29 (040308-192802242):496)
at com.google.android.gms.maps.internal.l.onTransact(:com.google.android.gms.dynamite_dynamitemodulesb#12529020#12.5.29 (040308-192802242):94)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.internal.zzeu.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzg.addMarker(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
Hi I have used like this and it's working fine for me
//generate bit map from view
private Bitmap createBitMap(View v) {
Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
if (b != null) {
Canvas c = new Canvas(b);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.draw(c);
}
return b;
}
// created user marker with his image
private void addMyLocationMarker() {
View view = DataBindingUtil.inflate(getActivity().getLayoutInflater(), R.layout.layout_marker, null, false);
view.setLayoutParams(new ViewGroup.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
view.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
if (userMarker != null)
userMarker = googleMap
.addMarker(new MarkerOptions()
.anchor(0.5F, 0.5F)
.position(latlng)
.icon(BitmapDescriptorFactory.fromBitmap(createBitMap(bindingUserMarker.getRoot()))));
userMarker.setZIndex(2f);
updateUserMarkerImage(view);
}
}
//update user image
private void updateUserMarkerImage(View view ) {
ImageView imageView=view.findViewById(R.id.image);
//load your image using any image loader and recreate marker with your view and set it marker
}

Grayscaling doesn't affect my image

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

Can't convert the relative layout with all the content to an image

I have the Relative Layout which has a scroll view and has more than 20 textviews.
when i try to convert this layout into a bitmap it is not happening
when i view it in an external storage it says "this file is damaged"
in gallery the image shows a black view
this is the code which i have used to convert the view to bitmap
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(dm.heightPixels, View.MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
v.draw(c);
return bitmap;
}
I have passed the object of relative layout to loadBitmapFromView.
and
I have used this code for saving image to external storage
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,1000,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
this is my logcat
12-30 15:02:20.397 24825-24825/com.google.android.gms.samples.vision.barcodereader W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
12-30 15:02:20.397 24825-24825/com.google.android.gms.samples.vision.barcodereader W/System.err: at com.google.android.gms.samples.vision.barcodereader.ResultActivity.SaveImage(ResultActivity.java:3483)
12-30 15:02:20.397 24825-24825/com.google.android.gms.samples.vision.barcodereader W/System.err: at com.google.android.gms.samples.vision.barcodereader.ResultActivity.onCreate(ResultActivity.java:137)
Your createBitmap function would be returning null, You try to obtain the bitmap like below.
final View v = mView.findViewById(R.id.your_view_id);
Bitmap b = Bitmap.createBitmap( v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
Try this
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(
v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
and use it as
Bitmap b = loadBitmapFromView(your_layout_object);

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

Categories