Java android bitmap = null for certain images - java

I' making an android app which allows the user to take a photo and then the app will print some RGB value etc. I'm saving the pictures taken on the phone and then I make a bitmap out of those png files. I just found out that I should sleep the application for a moment in order for the image to be saved. But I'm still getting that the bitmap is null for some images I take. If I take an image of Rubik's cube with it's 6 different colors I almost never get the null pointer exception. But if I take a picture of the wall or something else the bitmap is = null.
Does anyone know what I should do in order to fix this?
Bitmap myBitmap;
final String dir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
"/picFolder/";
try{
file = dir+Integer.toString(side)+".jpg";
File f = new File(file);
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
myBitmap = BitmapFactory.decodeFile(file,options);
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
cube[side-1][i][j] = getColor(myBitmap, i, j);
}
}
}catch (Exception e){
Log.e("er0r", "HERE:::: " + e.toString());
}

I also faced the same problem when I was developing camera in my app.
For some images it was working fine and for some images it was showing null.
Later I found that is a size issue.
I fixed that issue like this,
private static Bitmap compressBitmap(Bitmap original) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
return decoded;
}
Let me know if you need any other help.

Related

Screenshot of video

I am making an application where I want to take a screenshot. In foreground I am running some videos which are looping, also I have a background picture set. The problem is, when I take the screenshot, I get the background picture and not the picture of the video that runs.
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/app/" + fname + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(0, Mode.CLEAR);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 90;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
Log.d("MainActivity","TakeScreenshot SUCCESS");
//openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
Log.d("MainActivity","TakeScreenshot ERROR ");
e.printStackTrace();
}
Does anybody know how to take a snapshot of the video running on screen?

Getting current image from imageview (android)

I have an ImageView in which I load images from camera and gallery , and I do it using imgview.setimagebitmap(bitmap) ,( and I change the image again and again ) it works fine, but when I try to get the current image back for some processing (applying effect or rotate) it returns me the old image not the current one.
I think the problem is with imgview.setimagebitmap(bitmap).
can I be helped?
I have the following code:
try {
iv_image.buildDrawingCache();
Bitmap source = iv_image.getDrawingCache();
} catch(Exception ex) {
int a;
int b;
a = 11;
b = 12;
}
Can you please try to obtain the batman as follows :
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap()

Android How can I using Cursor get image and video thumbnails in my direct path both?

How can I using Cursor get image and video thumbnails in my direct path in same cursor?
I need get the image and video thumbnails in /DCIM/100ANDRO folder.
But I just can separate to get image and video in at sd card all data.
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
ContentResolver cr = mContext.getContentResolver();
String[] projection = {MediaStore.Images.Thumbnails.DATA, MediaStore.Video.Thumbnails.DATA};
Cursor cursor = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,projection,null,null,null);
for( int i = 0 ; i < cursor.getCount(); i++)
{
cursor.moveToPosition(i);
String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
Log.i("info","filePath:"+filePath);
File file = new File(filePath);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageItems.add( new ImageItem(myBitmap, "Image#" + i) );
}
cursor = cr.query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,projection,null,null,null);
for( int i = 0 ; i < cursor.getCount(); i++)
{
cursor.moveToPosition(i);
String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.i("info","filePath:"+filePath);
File file = new File(filePath);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageItems.add( new ImageItem(myBitmap, "Image#" + i) );
}
cursor.close();
return imageItems;
}
Have possible using cursor direct folder to get the thumbnails and get video and image thumbnails both?
thank you very much.
I found the answer.
We should inverse the method.
We can find the real path. then to get the ID.
Through the ID to get the images and videos thumbnails.
To get the images and videos using a cursor can refer the articles.
Getting images thumbnails using below code:
bitmap = MediaStore.Images.Thumbnails.getThumbnail(context
.getApplicationContext().getContentResolver(), item.getImgId(),
MediaStore.Images.Thumbnails.MICRO_KIND, null);
Getting video thumbnails using below code:
bitmap = MediaStore.Video.Thumbnails.getThumbnail(context
.getApplicationContext().getContentResolver(), item.getImgId(),
MediaStore.Images.Thumbnails.MICRO_KIND, null);

How to get byte[] from javafx imageView?

How do i get byte[] from javafx image/imageview class? I want to store my image as a Blob into my database.This is the method that i use for it
public PreparedStatement prepareQuery(HSQLDBConnector connector) {
try {
Blob logoBlob = connector.connection.createBlob();
logoBlob.setBytes(0,logo.getImage());//stuck here
for (int i = 0, a = 1; i < data.length; i++, a++) {
connector.prepStatCreateProfile.setString(a, data[i]);
}
//store LOB
connector.prepStatCreateProfile.setBlob(11, logoBlob);
} catch (SQLException ex) {
ex.printStackTrace();
}
return connector.prepStatCreateProfile;
}
Is there a way to convert from my current object (imageview),image) into byte[]?, or shoud i start to think about using other class for my image/ alternatively point to the location with reference and work with paths/urls?
try this one:
BufferedImage bImage = SwingFXUtils.fromFXImage(logo.getImage(), null);
ByteArrayOutputStream s = new ByteArrayOutputStream();
ImageIO.write(bImage, "png", s);
byte[] res = s.toByteArray();
s.close(); //especially if you are using a different output stream.
should work depending on the logo class
you need to specify a format while writing and reading, and as far as I remember bmp is not supported so you will end up with a png byte array on the database
pure java fx solution trace ( == you will have to fill in missing points :)
Image i = logo.getImage();
PixelReader pr = i.getPixelReader();
PixelFormat f = pr.getPixelFormat();
WriteablePixelFromat wf = f.getIntArgbInstance(); //???
int[] buffer = new int[size as desumed from the format f, should be i.width*i.height*4];
pr.getPixels(int 0, int 0, int i.width, i.height, wf, buffer, 0, 0);
Lorenzo's answer is correct, this answer just examines efficiency and portability aspects.
Depending on the image type and storage requirements, it may be efficient to convert the image to a compressed format for storage, for example:
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ImageIO.write(SwingFXUtils.fromFXImage(fxImage, null), "png", byteOutput);
Blob logoBlob = connector.connection.createBlob();
logoBlob.setBytes(0, byteOutput.toByteArray());
Another advantage of doing a conversion to a common format like png before persisting the image is that other programs which deal with the database would be able to read the image without trying to convert it from a JavaFX specific byte array storage format.

Creating bitmap from canvas java

SOLUTION
Thanks to #ChandraSekhar's suggestions the issue was that I was passing in an Immutable Bitmap to the canvas constructor. The solution is to create a copy of it when using BitmapFactory.decodeFile();
Bitmap bmp = BitmapFactory.decodeFile(imageURL).copy(Bitmap.Config.ARGB_8888, true);
So I have a bitmap that I am using bitmapFactory.decodeFile() for and this works. I am able to create the bitmap, then I need to create a canvas and this is where things get weird.
Here's the flow of what is happening.
I capture an image, then pass it to functionA that sizes it, and saves it out and returns its file path. ( I am using Phonegap Cordova )
I then pass that URL back to my java and use the previously saved image and manipulate it in functionB
CODE IN QUESTION:
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");
// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);
/* Everything works fine until this point */
// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap one = Bitmap.createBitmap(bmp);
canvas.drawBitmap(one,0,0,null);
I receive no errors, it just hangs. Here's the kick in the pants - if I run another function say functionB first that one works but the other doesn't.
I thought maybe I needed to flush and close my first FileOutputStream, but that didn't seem to have any effect. I've tried different variable names for all elements, bitmaps, canvas, and fileoutputstreams.
here is an example of the full function...
NOTE: Because I am using phonegap / cordova I am returning a string
public String none(JSONArray optionsArr) {
// SET FILE PATH
String filePath = "";
File path = new File(Environment.getExternalStorageDirectory()+"/myApp/");
// TMP.jpg is where we store our temporary version of the image
File NewFilePath = new File(path, "tmp_NBB.jpg");
// CREATE FOLDERS IF NEEDED
try{
boolean success = false;
if(!path.exists()){
success = path.mkdir();
}
if (!success){
Log.d("NONE","Folder not created.");
}
else{
Log.d("NONE","Folder created!");
}
}
catch (Exception e){
e.printStackTrace();
}
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");
// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);
// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap none = Bitmap.createBitmap(bmp);
canvas.drawBitmap(none,0,0,null);
// SAVE IMAGE
try {
// OUTPUT STREAM
FileOutputStream out = new FileOutputStream(NewFilePath);
none.compress(Bitmap.CompressFormat.JPEG, 100, out);
// GET FILE PATH
Uri uri = Uri.fromFile(NewFilePath);
filePath = uri.toString();
try{
out.flush();
out.close();
// RETURN FILE PATH
return filePath;
}
catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
Like I said this works for the first image, but when I attempt to open this image again, based on the returned filepath it chunks out at the create canvas line.
edit: The image path I am using looks like this:
/mtn/sdcard/myApp/tmp.jpg
thoughts?
Bitmap one = Bitmap.createBitmap(bmp);
In the above code bmp is a Bitmap and you are creating another Bitmap object one from bmp.
Remove that line and try by changing
canvas.drawBitmap(one,0,0,null);
to
canvas.drawBitmap(bmp,0,0,null);
Are you sure, the device on which you are running supports image size:655x655? Does bitmap get created?

Categories

Resources