I'm trying to write a simple "Paint"-like JavaFX-Application.
I draw on to a JavaFX.scene.canvas, this works quite well.
Now I want to save this canvas as a ".png" image. Works, but the transparent pixels where swapped with white ones.
How do I save transparent pixels, as transparent Pixels?
Here is how I save the canvas:
private void saveFile(){
FileChooser fc = new FileChooser();
fc.setInitialDirectory(new File("res/maps"));
fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PNG","*.png"));
fc.setTitle("Save Map");
File file = fc.showSaveDialog(primaryStage);
if(file != null){
WritableImage wi = new WritableImage((int)WIDTH,(int)HEIGHT);
try { ImageIO.write(SwingFXUtils.fromFXImage(canvas.snapshot(null,wi),null),"png",file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The problem is that when you snapshot the canvas, the first argument to snapshot is null, which means that default SnapshotParameters are used. In particular, the entire destination image is first filled with the SnapshotParameter's fill value. Since the argument is null, the default fill value is null, which means that the fill value (see SnapshotParameters.setFill) is white.
To fix this, just create a SnapshotParameters object, set its fill to transparent, and use it in the call to snapshot:
SnapshotParameters sp = new SnapshotParameters();
sp.setFill(Color.TRANSPARENT);
...
ImageIO.write(SwingFXUtils.fromFXImage(canvas.snapshot(sp, wi), null), "png", file);
Related
I'm trying to get the text input from the user and draw it on the image using Canvas but the image is saved without what was supposed to be drawn. Right now, I'm just trying to get the text on the Image before I worry about the font, colour, styles, etc.
This is my code:
public void createBitmapAndSave(ImageView img){
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(200);
paint.setStyle(Paint.Style.FILL);
paint.setShadowLayer(10f, 10f, 10f, Color.BLACK);
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
canvas.drawText(topText, 0, 0, paint);
canvas.drawText(bottomText, 50, 50, paint);
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/SimpliMeme/" + timeStamp + "-" + counter + ".jpg");
file.getParentFile().mkdir();
try{
OutputStream stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
}
catch (IOException e){ e.printStackTrace();}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
counter++;
}
At the moment, I only have the 2 .drawText() implementations based on the examples that I've seen in other SO posts. My assumption is that the text isn't visible and no changes are made to the image because I haven't provided the paint object with any attributes.
The main issue why you see no changes is that you make changes to mutableBitmap but save the original bitmap to disk.
This can be avoided by joining the first two (or even three) statements together:
final Bitmap bitmap = bitmapDrawable.getBitmap()
.copy(Bitmap.Config.ARGB_8888, true);
You didn't need the orginal bitmap anywhere else, this effectively prevents you from making the mistake. Don't do what you don't need to do.
Some tips:
Always be explicit when drawing. Specify the color, specify the font. You can't trust default values. (At least I'm never sure about the values. Is the default color black or transparent?)
If you want to be asolutely sure about the font, bundle it with your app or use downloadable fonts. Some platforms allow the user to change the default font to something crazy.
If you ever want to draw multiline text look into StaticLayout.
Make sure your app works on Android 7 and above. Sending intents with file Uri outside your app is prohibited.
How to save image in java as java.awt.image.IndexColorModel PNG? I'm loading indexed color png with ImageIO, manipulate it with Catalino library which unfortunately converts the color space to java.awt.image.DirectColorModel.
Now I want to save the result in the exactly same format as the original image. I tried the following snippet of code.
private static void testIndexedColor() throws IOException {
FastBitmap input = new FastBitmap("test.png");
BufferedImage bi = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
bi.getGraphics().drawImage(input.toBufferedImage(), 0, 0, null);
ImageIO.write(bi, "PNG", new File("test_result.png"));
}
But in the result weird light gray pixel artifacts appeared in the white background, and PPI decreased . How to correctly convert back to indexed color mode without quality loss and distortion?
Assuming I'm correct about the Catalano framework, you should be able to re-write your methods as this:
private static void testIndexedColor() throws IOException {
BufferedImage bi = ImageIO.read(new File("test.png"));
FastBitmap input = new FastBitmap(bi);
Graphics2D g = bi.createGraphics();
try {
g.drawImage(input.toBufferedImage(), 0, 0, null);
}
finally {
g.dispose(); // Good practice ;-)
}
ImageIO.write(bi, "PNG", new File("test_result.png"));
}
At least you should get away with the fixed palette and the artifacts.
However, this will likely still modify the PPI (but this won't affect the pixels). And even in some cases the image might be written back as a non-palette PNG.
Update: It seems the PNGImageWriter (through the PNGMetadata) actually re-writes an IndexColorModel containing a perfect grayscale, to a grayscale PNG by default. This is normally a good idea, as you reduce file size by not writing the PLTE chunk. You should be able to get around this, by passing the metadata from the original, along with the image pixel data, to instruct the writer to keep the IndexColorModel (ie. write PLTE chunk):
private static void testIndexedColor() throws IOException {
File in = new File("test.png");
File out new File("test_result.png");
try (ImageInputStream input = ImageIO.createImageInputStream(in);
ImageOutputStream output = ImageIO.createImageOutputStream(out)) {
ImageReader reader = ImageIO.getImageReaders(input).next(); // Will fail if no reader
reader.setInput(input);
ImageWriter writer = ImageIO.getImageWriter(reader); // Will obtain a writer that understands the metadata from the reader
writer.setOutput(output); // Will fail if no writer
// Now, the important part, we'll read the pixel AND metadata all in one go
IIOImage image = reader.readAll(0, null); // PNGs only have a single image, so index 0 is safe
// You can now access and modify the image data using:
BufferedImage bi = (BufferedImage) image.getRenderedImage();
FastBitmap fb = new FastBitmap(bi);
// ...do stuff...
Graphics2D g = bi.createGraphics();
try {
g.drawImage(fb.toBufferedImage(), 0, 0, null);
}
finally {
g.dispose();
}
// Write pixel and metadata back
writer.write(null, image, writer.getDefaultWriteParam());
}
}
This should (as a bonus) also keep your PPI as-is.
PS: For production code, you also want to dispose() of the reader and writer above, but I left it out to keep focus and avoid further discussion on try/finally. ;-)
I want to set the size of image get through json service. ???
Here is my code
public void getImage(){
try {
URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=good%20idea%20good%20idea%20water%20jug%20water%20jug%20thirsty%20crow%20thirsty%20crow%20long%20time%20long%20time%20jug%20jug");
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
String imageUrl = json.getJSONObject("responseData").getJSONArray("results").getJSONObject(0).getString("url");
BufferedImage image = ImageIO.read(new URL(imageUrl));
ImageIcon img = new ImageIcon(image);
JLabel label = new JLabel("", img, JLabel.CENTER);
jPanel1.add( label, BorderLayout.CENTER );
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
I am showing the image in a jPanel.I want to set the size of image so it must be smaller than panel size. How could I achieve this ????
If you don't care about the quality of the result, you could use Image#getScaledInstance, but you should have a read of The Perils of Image.getScaledInstance() of first
Image scaled = image.getScaledInstance(jPanel1.getWidth(), jPanel1.getHeight(), Image.SCALE_SMOOTH);
But this won't maintain the aspect ratio of the image, to do that, you'd have to decide which dimension is more important
int width = jPanel1.getWidth();
int height = jPanel1.getHeight();
if (width < height) {
height = -1;
} else {
width = -1;
}
Image scaled = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
Have a look at Java: maintaining aspect ratio of JPanel background image for more details
Now, if you do care about the quality of the resulting image, then you need to use a different scaling approach, you could use something like a divide and conqure approach, as demonstrated in Quality of Image after resize very low -- Java or use a 3rd party library, like ImgSclr
Now, you next problem is, the size of a component is generally calculated based on the needs of it's children. In this case, that means that jPanel1 may want to use the size of the JLabel to determine how large it should be. Equally, the JLabel will use the size of the image to determine how large it should be. Which puts you in a catch 22 problem.
You could use a JScrollPane which will allow the image to occupy a large area then is available or you will need a dynamic panel which can resize the image automatically based on the available space, but you would still need to make a determination of what the "default" or "preferred" size should be
try this:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);
I try to draw an image from a bufferedImage into a PDF using PDFBox but fails, and I get black images and Acrobat Reader warns whith errors like "Out of memory" (but PDF is display).
I use a bufferedImage because I need to draw a JavaFX Image object (with came from call to Funciones.crearImagenDesdeTexto(), is a function which converts a text into an Image) into PDF. Rest of images works well without using bufferedimage.
PDPixelMap img = null;
BufferedImage bi;
try {
//If item has id, I try to get image with that id (image it's shows OK on PDF)
img = new PDPixelMap(documento, read(getClass().getResourceAsStream("/com/img/" + item.getId() + ".png")));
}
catch (Exception e) {
//If item has not id or fails load image, I create image on the fly (which contains item name. This not work on PDF, shows black images)
bi = new BufferedImage(alto, ancho, BufferedImage.TYPE_INT_ARGB);
bi.createGraphics().drawImage(SwingFXUtils.fromFXImage(Funciones.crearImagenDesdeTexto(item.getNombre()), null), ancho, alto, null);
img = new PDPixelMap(documento, bi);
}
finally {
contenedor.drawXObject(img, x, y, alto, ancho);
}
NOTE: crearImagenDesdeTexto() returns a JavaFX Image Object that is create on the fly (I try this function in other parts of the program and works well, function is take from other stackOverflow response).
Your code is confusing, you have three "new PDJpeg" and one of them is in a catch (which should just handle the error). And what does "read()" do? Does it pass a stream or a BufferedImage? If it is a stream, then it is wrong, because PDJpeg is for JPEGs, not for PNG.
The second one
img = new PDJpeg(documento, (getClass().getResourceAsStream("/com/img/" + Byte.toString(item.getId()) + ".png")));
is definitively wrong for the same reason: PDJPeg is not for PNG files / streams.
If you want to create an image from a PNG file / stream, use PDPixelMap.
It is possible to create a PDJpeg object from a BufferedImage, but this is recommended only if the image wasn't encoded before. Because if you would read a BufferedImage from a JPEG, and then use PDJPeg for this, you'll have a slight loss of quality as the image is decoded and encoded again (JPEG is a "lossy" compression format).
If my advice doesn't help, please upload the JPEG file and the PDF somewhere.
Also make sure that you're using the latest version, which is 1.8.7.
Update after comments:
the parameters to createGraphics.drawImage() should be 0, 0 and not width, height. The two parameters are a location, not a size.
Finally, I find a solution (thanks also to Tilman Hausherr):
private void dibujarImagen(Item i, int x, int y, int alto, int ancho) throws IOException {
PDPixelMap img = null;
try {
img = new PDPixelMap(documento, read(getClass().getResourceAsStream("/com/img/" + i.getId() + ".png")));
}
catch (IllegalArgumentException e) {
img = new PDPixelMap(documento, SwingFXUtils.fromFXImage(Funciones.crearImagenDesdeTexto(i.getNombre()),null));
}
finally {
contenedor.drawXObject(img, x, y, alto, ancho);
}
}
I am working with Java and combine two images. I save the combined image and want to delete the overlay, but it seems there are still streams open. And i don't know which and how to close them.
f_overlay and f_image are both Files.
// load source images
BufferedImage image = null;
BufferedImage overlay = null;
try {
log.debug(f_image.getAbsolutePath());
log.debug(f_overlay.getAbsolutePath());
image = ImageIO.read(f_image);
overlay = ImageIO.read(f_overlay);
} catch (IOException e) {
log.error(e.getMessage());
}
// create the new image, canvas size is the max. of both image sizes
int w = Math.max(image.getWidth(), overlay.getWidth());
int h = Math.max(image.getHeight(), overlay.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// paint both images, preserving the alpha channels
Graphics g = combined.getGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage(overlay, 0, 0, null);
// Save as new image
try {
ImageIO.write(combined, "PNG", f_image);
} catch (IOException e) {
log.error(e.getMessage());
}
// we can delete the overlay now
log.debug("Delete overlay: " + f_overlay.delete());
Are there any suggestions?
I can't see anything wrong in your code.
However, I would only delete the file f_overlay if the reading was successful. Important, after you call delete() on the file object, you must not use the object for anything else, so best is to assign f_overlay=null
boolean state = f_overlay.delete();
f_overlay=null;
log.debug("Delete ... "+state);