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);
Related
I'm trying to store an imageIcon bas a Base64 String.
This is what I have so far:
public ImageIcon getImageIcon() {
if(imageIcon == null || imageIcon.isEmpty()){
return null;
} else {
try {
byte[] btDataFile = Base64.decodeBase64(imageIcon);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(btDataFile));
return new ImageIcon(image);
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
return null;
}
}
}
public void setImageIcon(ImageIcon imageIconIn) {
imageIcon = Base64.encodeBase64String(imageToByteArray(imageIconIn));
}
public static byte[] imageToByteArray(ImageIcon imageIn) {
try {
BufferedImage image = new BufferedImage(imageIn.getIconWidth(), imageIn.getIconHeight(),BufferedImage.TYPE_INT_RGB);
ByteArrayOutputStream b = new ByteArrayOutputStream();
// FIX
Graphics g;
g = image.createGraphics();
imageIn.paintIcon(null, g, 0,0);
// END FIX
ImageIO.write(image, "jpg", b );
g.dispose();
return b.toByteArray();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
return null;
}
}
I get a black rectangle instead of the image.
I'm using Java 1.8 on Ubuntu 16.04.
What am I doing wrong?
Thanks for your help.
******************************** . FIXED . ******************************
I found a working solution and updated the above code.
******************************** EDIT *********************************
Added g.dispose() after painting icon.
This code creates a brand new BufferedImage, with width & height same as the given image.
BufferedImage image = new BufferedImage(
imageIn.getIconWidth(),
imageIn.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Note that the image is empty. No content has been written to it. The bytes will all be zero, and RGB 0x000000 is black.
Then, you are writing the bytes of this black image to your ByteArrayOutputStream.
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", b );
return b.toByteArray();
Of course, when you convert that byte buffer back to an image, it will be black.
You will want to draw/copy imageIn into your new image before you write out the bytes.
But if you don't mind using whatever the current image's format is, you could just write out that image instead of converting it to TYPE_INT_RGB...
Image image = imageIn.getImage();
// write image to ByteArrayOutputStream
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 am inserting image in using this
var readFileIntoDataUrl = function (fileInfo) {
var loader = $.Deferred(),
fReader = new FileReader();
fReader.onload = function (e) {
loader.resolve(e.target.result);
};
fReader.onerror = loader.reject;
fReader.onprogress = loader.notify;
fReader.readAsDataURL(fileInfo);
return loader.promise();
};
$.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
execCommand('insertimage', dataUrl);
}).fail(function (e) {
options.fileUploadError("file-reader", e);
});
Let say i added a text Hello World and added a image. Now when i take $("#editor").html() it shows something like below
Here is a sample source of a image+text
Hello World!
img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgA
BAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAA
AQAAAGAAAAABUGFpbnQuTkVUIHYzLjUuOAAA/9sAQwAHBQUGBQQHBgUGCAcHCAoRCwoJCQoVDxAMERgV
[... more base64 data here....]
Now here i have both text+image So both on server side and client side i want to resize & compress image
So that no one can insert image > 5MP and also keep a rich text with resize image in my db
This is how you can do it on the server side (Java):
String imageData = "Hello World! img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoR...";
//Image data starting point
int startIndex = imageData.indexOf(";base64,") + ";base64,".length();
//keep only the image data
imageData = imageData.substring(startIndex, imageData.length());
//convert the image data String to a byte[]
byte[] dta = DatatypeConverter.parseBase64Binary(imageData);
try (InputStream in = new ByteArrayInputStream(dta);) {
BufferedImage fullSize = ImageIO.read(in);
// Create a new image half the size of the original image
BufferedImage resized = new BufferedImage(fullSize.getWidth() / 2, fullSize.getHeight() / 2, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = (Graphics2D) resized.getGraphics();
g2.drawImage(fullSize, 0, 0, resized.getWidth(), resized.getHeight(), 0, 0, fullSize.getWidth(), fullSize.getHeight(), null);
g2.dispose();
} catch (IOException e) {
e.printStackTrace();
}
As for the JavaScript part you can use a canvas, size the canvas to the dimension that you want, draw your image on it and use the toDataURL method to convert the image to a String
I created a directory and then listed the files inside the directory in an array. All the files in the directory are .png files. When I print the array out in the console, the pictures are called thumbs.db
public static void PictureOverlay1() throws IOException {
overlay = ImageIO.read(new File(overlayPath2, ""));
image = ImageIO.read(new File(imagePath, ""));
if (!path.exists()) {
System.out.println("Creating File");
path.mkdir();
} else {
System.out.println("Already Created");
// 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
ImageIO.write(combined, "PNG", new File("C:/Users/Daniel/Documents/Brain Bang/Coding/Minecraft Modding/New Mods/1.6.4 Television Mod/forge/mcp/src/minecraft/assets/tvmod/textures/blocks/combined.png"));
}
}
You wrote:
All the files in the directory are .png files.
I don't think so. Since you have a result called thumbs.db, I guess you're on a Windows machine. Windows adds two files into each directory:
desktop.ini
thumbs.db
You should skip these two files (or just every hidden file - Windows automatically marks the files as hidden ones).
I am using an Applet to save image from clipboard. The image is saved but something happened with its format. It is darken and lost colors.
here's how I am doing it:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
//create clipboard object
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
//file that we'll save to disk.
File file = new File("/tmp/clipboard.jpg");
//class to write image to disk. You specify the image to be saved, its type,
// and then the file in which to write the image data.
ImageIO.write(image, "jpg", file);
//getData throws this.
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
return "Não tem imagem na área de transferência";
} catch (Exception ioe){
ioe.printStackTrace();
}
return null;
}
}
);
I read that Mac uses a different image format but I did not find how to convert it to a format I could save. I imagined that java should have taken care of that.
So, how can I convert the image from clipboard to jpg?
PS. I tried using png instead of jpg, got a worse result: black image
To solve the issue on Mac, I used the solution proposed on The nightmares of getting images from the Mac OS X clipboard using Java.
I pass the retrieved BufferedImage to method that redraws it to new BufferedImage, returning a valid image. Here follows the code from that page:
public static BufferedImage getBufferedImage(Image img) {
if (img == null) return null;
int w = img.getWidth(null);
int h = img.getHeight(null);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage bufimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufimg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return bufimg;
}
And how I use it:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
if (isMac()) {
image = getBufferedImage(image);
}
PNG is the preferred image format for Macs. You might want to try saving as that and then converting to a JPG if needed afterwards.