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?
Related
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.
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?
I need to decode an .png image to use it as a base to create some Rects and to use the image itself as a background for my application, but the try-catch keeps throwing me a Null Pointer Exception, this is the code:
try {
InputStream is = ParamsSingleton.assetManager.open("background.png");
figure = BitmapFactory.decodeStream(is);
height = figure.getHeight();
width = figure.getWidth();
src = new Rect(0, 0, width, height);
first = new Rect();
} catch (IOException e) {
Log.d(TAG, "Image decode fail!");
}
I've tried some logs and the try-catch break right on the InputStream line and prints the 'Log.d' in catch block, I checked the file name and it is alright.
You can directly use getAssets.open method inside decodeStream .
figure = BitmapFactory.decodeStream(getAssets.open("background.png"));
I have a problem with Java application, particular in loading a image from a location in my computer.
Following this post I used a BufferedImage and a InputFileStream to load an image on my computer. First, I put the image (pic2.jpg) into the source code and that is working. However, if I put the image to another place (let's say C:\\ImageTest\pic2.jpg), Java IDE show me an IllegalArgumentException
return ImageIO.read(in);
here is the code:
public class MiddlePanel extends JPanel {
private BufferedImage img;
public MiddlePanel(int width) {
//img = getImage("pic2.jpg");
img = getImage("C:\\ImageTest\\pic2.jpg");
this.setPreferredSize(new Dimension(800,460));
}
public void paintComponent(Graphics g) {
// ...
}
private BufferedImage getImage(String filename) {
// This time, you can use an InputStream to load
try {
// Grab the InputStream for the image.
InputStream in = getClass().getResourceAsStream(filename);
// Then read it.
return ImageIO.read(in);
} catch (IOException e) {
System.out.println("The image was not loaded.");
//System.exit(1);
}
return null;
}
}
To read an .jpg file from non-relative path you could use this:
BufferedImage img = null;
try
{
img = ImageIO.read(new File("C:/ImageTest/pic2.jpg")); // eventually C:\\ImageTest\\pic2.jpg
}
catch (IOException e)
{
e.printStackTrace();
}
I do not have any Java environment at the moment, so hope it works and is written correctly.
getResource & getResourceAsStream do not work with file paths, but paths relative the code base. If the code base is C: then a relative path that would locate the resource is /ImageTest/pic2.jpg.
..difference between load file by FileInputStream and getResourceAsStream?
One major difference is that the getResource.. will work with a resource inside a Jar, which is no longer a File. Therefore FileInputStream cannot be used to access such a resource.
You cannot use Class#getResource(String) or Class#getResourceAsStream(String) in this case. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a / (\u002f), then the absolute name of the resource is the portion of the name following the /.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with / substituted for . (\u002e).
Generally, it is not a good thing to hard code the system location of your resources in your code. The neat and clean way is to put your resources in your classpath and access them. Hope this clarifies why it's not working
//This code snippet read an image from location on the computer and writes it to a different location on the disk
try {
byte[] imageInByte;
BufferedImage imageOnDisk = ImageIO.read(new File("C:\\ImageTest\\pic2.jpg"));
//Create a ByteArrayOutputStrea object to write image to
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Write the image to the OutputStream
ImageIO.write(imageOnDisk, "jpg", baos);
baos.flush();
//Initialise the byte array object with the image that was written to the OutputStream
imageInByte = baos.toByteArray();
baos.close();
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(in);
//write the image to a new location with a different file name(optionally)
ImageIO.write(bImageFromConvert, "jpg", new File(
"c:\\index.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
To find the image Width, height and size
BufferedImage image = null;
int imageWidth = -1;
int imageHeight = -1;
int fileSize = -1;
try {
File imageFile = new File(imagePath);
int fileSize = (int) imageFile.length();
image = ImageIO.read(imageFile); // Reading the Image from the file system
imageWidth = image.getWidth();
imageHeight = image.getHeight();
} catch (IOException e) {
e.printStackTrace();
}
Im trying to add a image from a URL address to my pdf. The code is:
Image image=Image.getInstance("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
image.scaleToFit((float)200.0, (float)49.0);
paragraph.add(image);
But it does not work. What can be wrong?
This is a known issue when loading .gif from a remote location with iText.
A fix for this would be to download the .gif with Java (not via the getInstance method of iText's Image class) and to use the downloaded bytes in the getInstance method of the Image class.
Edit:
I went ahead and fixed remote gif loading in iText, it is included from iText 5.4.1 and later.
Adding Image into Itext PDF is not possible through URL .
Only way to add image in PDF is download all images in to local directory and apply below code
String photoPath = Environment.getExternalStorageDirectory() + "/abc.png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap.createScaledBitmap(b, 10, 10, false);
b.compress(Bitmap.CompressFormat.PNG, 30, stream);
Image img = null;
byte[] byteArray = stream.toByteArray();
try {
img = Image.getInstance(byteArray);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The way you have used to add images to IText PDF is the way that is used for adding local files, not URLs.
For URLs, this way will solve the problem.
String imageUrl = "http://www.google.com/intl/en_ALL/"
+ "images/logos/images_logo_lg.gif";
Image image = Image.getInstance(new URL(imageUrl));
You may then proceed to add this image to some previously open document, using document.add(image).
For further reference, please visit the [Java IText: Image docs].