Java: using WritableRaster.setRect to superimpose an image? - java

I have been playing with some of the imaging functionality in Java, trying to superimpose one image over another. Like so:
BufferedImage background = javax.imageio.ImageIO.read(
new ByteArrayInputStream(getDataFromUrl(
"https://www.google.com/intl/en_ALL/images/logo.gif"
))
);
BufferedImage foreground = javax.imageio.ImageIO.read(
new ByteArrayInputStream(getDataFromUrl(
"https://upload.wikimedia.org/wikipedia/commons/e/e2/Sunflower_as_gif_small.gif"
))
);
WritableRaster backgroundRaster = background.getRaster();
Raster foregroundRaster = foreground.getRaster();
backgroundRaster.setRect(foregroundRaster);
Basically, I was attempting to superimpose this: https://upload.wikimedia.org/wikipedia/commons/e/e2/Sunflower_as_gif_small.gif
on this: https://www.google.com/intl/en_ALL/images/logo.gif
The product appears as: http://imgur.com/xnpfp.png
From the examples I have seen, this seems to be the appropriate method. Am I missing a step? Is there a better way to handle this? Thank you for your responses.

Seems I was going about this in all the wrong ways. This solution outlined on the Sun forums works perfectly (copied here):
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class TwoBecomeOne {
public static void main(String[] args) throws IOException {
BufferedImage large = ImageIO.read(new File("images/tiger.jpg"));
BufferedImage small = ImageIO.read(new File("images/bclynx.jpg"));
int w = large.getWidth();
int h = large.getHeight();
int type = BufferedImage.TYPE_INT_RGB;
BufferedImage image = new BufferedImage(w, h, type);
Graphics2D g2 = image.createGraphics();
g2.drawImage(large, 0, 0, null);
g2.drawImage(small, 10, 10, null);
g2.dispose();
ImageIO.write(image, "jpg", new File("twoInOne.jpg"));
JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
JOptionPane.PLAIN_MESSAGE);
}
}

Related

Merge images in Java

I am trying to merge two images in Java. The two photos must be positioned horizontally (the first to the left of the second).
I think I have problems in the write method of the ImageIO class.
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;
public class Merge {
public static void main(String[] args) throws IOException {
String p = "../../Desktop/temp/";
BufferedImage left = ImageIO.read(new File(p+"006.jpg"));
BufferedImage right = ImageIO.read(new File(p+"007.jpg"));
BufferedImage imgClone = new BufferedImage(left.getWidth()+right.getWidth(), left.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D cloneG = imgClone.createGraphics();
cloneG.drawImage(right, 0, 0, null);
cloneG.drawImage(left, left.getWidth(), 0, null);
System.out.println(ImageIO.write(imgClone, "jpg", new File(p+"001.jpg"))); //always false
cloneG.dispose();
}
}
ImageIO.write(imgClone, "jpg", new File(p+"001.jpg")) always returns false, I think there is something wrong here but I can't figure out what.
If I go into debugging I can see the merged photo, but then it won't be saved in the folder.
I think it's because JPEG doesn't support transparency, and you used ARGB as the image buffer type. Removing the "A" worked for me.
class Merge {
public static void main(String[] args) throws IOException {
BufferedImage imgClone = new BufferedImage( 50, 50, BufferedImage.TYPE_INT_RGB);
// returns "true"
System.out.println(ImageIO.write(imgClone, "jpg", File.createTempFile( "Test-", "jpg")));
}
}

Bengali Joint letters in Kalpurush font in java messed up

I have written a program (collecting from various sources, I am a beginner) in Java that takes a text(bengali) written in a .txt file and converts it to a .bmp image using the drawString function. The code is :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.*;
import java.awt.font.*;
import java.awt.geom.*;
class TextToImageDemo
{
public static void main(String[] args) throws IOException
{
String sampleText = "আমার",s="নাম";
BufferedReader br = null;
for (int u=1;u<=9;u++)
{
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\Java\\bengtext\\f2-0"+u+".txt")),"UTF-8"));
while ((sampleText = br.readLine()) != null)
{
System.out.println(sampleText);
s=sampleText;
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
//Image file name
String fileName = "Image";
//create a File Object
File newFile= new File("./" + fileName + ".jpeg");
//create the font you wish to use
Font font = new Font(/*Lohit Bengali*/"Kalpurush", Font.PLAIN, 50);
//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
//create a BufferedImage object
BufferedImage image = new BufferedImage(2000, 200, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
System.out.println(s);
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, 2000, 200);
g.setColor(Color.BLACK);
g.setFont(font);
FontMetrics fm=g.getFontMetrics();
Rectangle r=new Rectangle(fm.getStringBounds(s, g).getBounds());
String d=s.substring(1,s.length());
g.drawString(d, image.getWidth()/2-r.width/2, image.getHeight()/2+r.height/2);
//releasing resources
g.dispose();
try
{
FileOutputStream fos = new FileOutputStream("E:\\Java\\bengtext\\f2-0"+u+".bmp");
ImageIO.write(image,"bmp",fos);
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
My main problem lies in the fact that a text like
দ্বিতীয়তা , একাগ্রতা , " জ্ঞান আহরনের একটি মাত্র উপায়
is formed like
How can this be solved?
Edit:
On checking all the 263 fonts available , I found only 6 of them were able to display bengali somewhat correctly. But in everyone of them the problem with the joint words lie as shown in the above picture. So question is : What is the exact problem happening here? Is JAVA not being able to read the joint words correctly, or is it not being able to draw them correctly ?
And secondly , how to make java draw the joint words correctly?

Fastest method for blurring an image in java

Edit I'm using Eclipse ADT bundle but when I try importing the library in the suggested answer above it doesn't work.
I'm using a combination of LibGDX and Java (90-99% java) to blur an image. The blur works but it takes nearly a second to take a screenshot, save it, access it, blur it, save it, and re-access it. I can't do much pre-processing because it takes a screenshot of the game to blur. Here is what I'm using currently for blurring: (I'll put drawing and screenshots up if you need to see them, but I think the issue lies in the blurring of an 800x480 png.)
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
public class Blur {
private static BufferedImage mshi;
private BufferedImage databuf;
private static int blurRad = 300;
public static void createBlur(FileHandle file) throws IOException {
mshi = ImageIO.read(file.file());
BufferedImage databuf = new BufferedImage(mshi.getWidth(null),
mshi.getHeight(null),
BufferedImage.TYPE_INT_BGR);
java.awt.Graphics g = databuf.getGraphics();
g.drawImage(mshi, 455, 255, null);
float[] blurKernel = new float[blurRad*blurRad];
for(int i =0; i<blurRad*blurRad; i++) {
blurKernel[i] = 1.0f/256.0f;
}
BufferedImageOp op = new ConvolveOp( new Kernel(20, 20, blurKernel), ConvolveOp.EDGE_ZERO_FILL, null );
mshi = op.filter(mshi, databuf);
g.dispose();
File outputfile = Gdx.files.local("Blur.png").file();
ImageIO.write(mshi, "png", outputfile);
}
}

Need help to remove exception in my java graphics code

I am developing an application in swing which has 5 tabs with following 5 operations on an image :No Operation ,Color Convert ,Affine Transform ,Convolve and Look Up.
Here is the code :
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.LookupTable;
import java.awt.image.ShortLookupTable;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class ImageProcessing extends JFrame{
BufferedImage source;
public static void main(String args[])
{
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e1){e1.printStackTrace();}
SwingUtilities.invokeLater(new Runnable(){public void run(){new ImageProcessing();}});
}
public ImageProcessing() {
// TODO Auto-generated constructor stub
super("Image Processing");
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
source=ImageIO.read(new File("src/abc.jpg"));
}catch(IOException e){System.out.println("Exception Here :"+e);}
JTabbedPane jtp=new JTabbedPane();
buildNoOpTab(jtp);
buildAffineTransformOpTab(jtp);
buildColorConvertOpTab(jtp);
buildConvolveOpTab(jtp);
buildLookUpOpTab(jtp);
//buildRescaleOpTab(jtp);
add(jtp);
setVisible(true);
}
private void buildNoOpTab(JTabbedPane jtp)
{
jtp.add("No Op",new JLabel(new ImageIcon(source)));
}
private void buildAffineTransformOpTab(JTabbedPane jtp)
{
BufferedImage dst;
AffineTransform transform=AffineTransform.getScaleInstance(0.5, 0.5);
AffineTransformOp op=new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
dst=op.filter(source, null);
jtp.add("AffineTransform",new JLabel(new ImageIcon(dst)));
}
private void buildColorConvertOpTab(JTabbedPane jtp)
{
BufferedImage dst = null;
ColorSpace clr=ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op=new ColorConvertOp(clr,null);
dst=op.filter(source,dst);
jtp.add("Color Convert",new JLabel(new ImageIcon(dst)));
}
private void buildConvolveOpTab(JTabbedPane jtp) {
BufferedImage dst = null;
float sharpen[] = new float[] {
0.0f, -1.0f, 0.0f,
-1.0f, 5.0f, -1.0f,
0.0f, -1.0f, 0.0f
};
Kernel kernel = new Kernel(3, 3, sharpen);
ConvolveOp op = new ConvolveOp(kernel);
dst = op.filter(source, null);
jtp.add("Convolve", new JLabel(new ImageIcon(dst)));
}
private void buildLookUpOpTab(JTabbedPane jtp)
{
BufferedImage dst=null;
short[] data=new short[256];
for(int i=0;i<256;i++)
data[i]=(short)(255-i);
LookupTable lkp=new ShortLookupTable(0,data);
LookupOp op=new LookupOp(lkp,null);
dst=op.filter(source, null);
jtp.add("Look Up",new JLabel(new ImageIcon(dst)));
}
}
There is some problem in the buildLookUpOpTab as removing this method application works fine.
Here is the exception which I am getting:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
Number of color/alpha components should be 3 but length of bits array is 1
at java.awt.image.ColorModel.<init>(ColorModel.java:336)
at java.awt.image.ComponentColorModel.<init>(ComponentColorModel.java:273)
at java.awt.image.LookupOp.createCompatibleDestImage(LookupOp.java:413)
at java.awt.image.LookupOp.filter(LookupOp.java:153)
at ImageProcessing.buildLookUpOpTab(ImageProcessing.java:108)
at ImageProcessing.<init>(ImageProcessing.java:49)
at ImageProcessing$1.run(ImageProcessing.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Can anyone tell me what is the problem in that method?
The LookupOp.filter method says that:
Performs a lookup operation on a BufferedImage. If the color model in the source image is not the same as that in the destination image, the pixels will be converted in the destination. If the destination image is null, a BufferedImage will be created with an appropriate ColorModel. An IllegalArgumentException might be thrown if the number of arrays in the LookupTable does not meet the restrictions stated in the class comment above, or if the source image has an IndexColorModel.
Since you are filtering a BufferedImage created from using ImageIO.read, the color model that the image will have will definitely not be IndexColorModel, since JPEGImageReader (which actually created the BufferdImage from the file) does not support IndexColorModel - in the olden days, JPEGs used the DirectColorModel
Have a look at the answer on this thread on how to read a JPEG file and use a different color model:
Unable to read JPEG image using ImageIO.read(File file)
You need to remove alpha channel from your image before using any filter on it. To make your code working, change:
try
{
source=ImageIO.read(new File("src/abc.jpg"));
} catch(IOException e){System.out.println("Exception Here :"+e);}
with this:
try
{
BufferedImage src = ImageIO.read(new File("abc.jpg"));
int w = src.getWidth();
int h = src.getHeight();
source = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Raster raster = src.getRaster().createChild(0, 0, w, h, 0, 0,
new int[] {0, 1, 2});
source.setData(raster);
}catch(IOException e){System.out.println("Exception Here :"+e);}
The above code creates a new buffered image in RGB mode and set the RGB data of original image to new buffered image ignoring the alpha values. But in case your original image contains completely transparent spots then it will become black spots in new buffered image.

Does anyone have an example of Apache POI converting PPTX to PNG

Does anyone know of a good example of converting a PPTX powerpoint presentation to some form of image? PNG/GIF/etc?
I can do it for a PPT but looking for a PPTX conversion example
Thanks
In the meantime it works (... copied it from there):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public class PptToPng {
public static void main(String[] args) throws Exception {
FileInputStream is = new FileInputStream("example.pptx");
XMLSlideShow ppt = new XMLSlideShow(is);
is.close();
double zoom = 2; // magnify it by 2
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Dimension pgsize = ppt.getPageSize();
XSLFSlide[] slide = ppt.getSlides();
for (int i = 0; i < slide.length; i++) {
BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setTransform(at);
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
slide[i].draw(graphics);
FileOutputStream out = new FileOutputStream("slide-" + (i + 1) + ".png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
}
}
}
Answering my own question, I subscribed to the development mailing list and asked this question.
The answer is that this functionailty is currently not supported by apache poi
There's an example class PPTX2PNG now bundled with POI that seems to work with decent results for the PPTX decks I've thrown at it:
http://svn.apache.org/repos/asf/poi/trunk/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java
pptx4j can help you to create SVG in HTML (though there is still work to do to support all shapes); and then you could use one of the tools which create a image from an automated browser window.

Categories