while running the program to grab frames from web cam captured video i am getting facing problem of NullPointerException. i tried to change the settings of capture devices but ther is no option like
"vfw:Microsoft WDM Image Capture (Win32):0"
cant locate device in jmf.
.so is mentioned directly into the code refering to the materials.but not working!
i am using net beans for this and libraries of jmf also included in netbeans.
please help me fix this.my code:
package VideoSource;
/**
*
* #author sri
*/
import java.awt.Frame;
import javax.imageio.ImageIO;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.media.Buffer;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.CaptureDeviceInfo;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.media.*;
public class frames {
public static final String DEVICE ="vfw:Microsoft WDM Image Capture (Win32):0";
//protected Player player;
public static void main(String args[]) throws IOException, CannotRealizeException{
try{
CaptureDeviceInfo cdi = CaptureDeviceManager.getDevice(DEVICE);
Player player = Manager.createRealizedPlayer(cdi.getLocator());
player.start();
FrameGrabbingControl frameGrabber = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = frameGrabber.grabFrame();
//BufferedImage buf1 = frameGrabber.grabFrame();
// Convert frame to an buffered image so it can be processed and saved
Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf));
if(img!=null){
RenderedImage img1=(RenderedImage) img;
int i=0;
File outputfile = new File("d:/Project/frame"+(i++)+".jpg");
ImageIO.write(img1, "jpg", outputfile);
}
else
System.out.println("null from frame grabbing");
//return img;
}
catch(NoPlayerException n)
{
}
}
}
i have exception as:
Exception in thread "main" java.lang.NullPointerException
at VideoSource.frames.main(frames.java:37)
Java Result: 1
Related
I have a piece of code
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
public class Characters {
public static void main (String [] args) throws AWTException, InterruptedException {
TimeUnit.SECONDS.sleep(3);
Robot newRobot = new Robot();
StringSelection stringSelection;
Clipboard clipboard;
String text;
for (int i = 1; i <= 2; i++) {
TimeUnit.MILLISECONDS.sleep(1000);
text = String.valueOf(i);
stringSelection = new StringSelection(text);
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
if(i % 2 == 1) {
TimeUnit.MILLISECONDS.sleep(100);
newRobot.mouseMove(1141, 852);
newRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
newRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} else {
TimeUnit.MILLISECONDS.sleep(100);
newRobot.mouseMove(444, 859);
newRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
newRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
TimeUnit.MILLISECONDS.sleep(900);
newRobot.keyPress(KeyEvent.VK_CONTROL);
newRobot.keyPress(KeyEvent.VK_V);
newRobot.keyRelease(KeyEvent.VK_V);
newRobot.keyRelease(KeyEvent.VK_CONTROL);
newRobot.keyPress(KeyEvent.VK_ENTER);
}
}
}
On my Windows PC, if I changed applications, it would run the clicks and keys on said application, I have an original 3 second sleep to change applications. On my Mac, when the mouseMove part starts, it automatically changes the application back to Netbeans when I don't want that. Any setting to change that?
Hello all So I'm making progress on my animation program but I'm running into a problem where my alien.png isn't showing up in the jframe. I have the alien.png in the same folder as this animation demo.java so I'm not sure why its not finding the alien.png. Any help would be appreciated
package animationdemo;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AnimationDemo extends JFrame {
Image alien;
public AnimationDemo() {
alien = Toolkit.getDefaultToolkit().getImage("alien.png");
MovingMessagePanel messagePannel = new MovingMessagePanel();
messagePannel.alien = this.alien;
Timer timer = new Timer(50, messagePannel);
timer.start();
this.add(messagePannel);
}
public static void main(String[] args) {
AnimationDemo frame = new AnimationDemo();
frame.setTitle("Project 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
class MovingMessagePanel extends JPanel implements ActionListener {
public int xCoordinate = 20;
public int yCoordinate = 20;
public int xDir=5;
public int yDir=5;
public Image alien;
public void actionPerformed(ActionEvent e) {
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (xCoordinate > getWidth()) xDir*=-1;
if (yCoordinate > getHeight()) yDir*=-1;
if (xCoordinate <0) xDir*=-1;
if (yCoordinate <0) yDir*=-1;
xCoordinate += xDir;
yCoordinate += yDir;
g.drawImage(alien,xCoordinate,yCoordinate,this);
}
}
Let's look at the code lines:
package animationdemo; // this one!
import java.awt.Graphics;
// ..
public class AnimationDemo extends JFrame {
Image alien;
public AnimationDemo() {
alien = Toolkit.getDefaultToolkit().getImage("alien.png"); // & this one!
That last line is effectively trying to load a File from the 'current directory'.
But the image probably won't be accessible as a File any longer. Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
Note given the first highlit line, the best path for finding the resource would presumably be:
..getResource("/animationdemo/alien.png")
Note also that the getResource method is case sensitive, so ..
..getResource("/animationdemo/alien.PNG")
.. won't find the lower case version, nor vice-versa.
As an aside, I did a check of my 'missing image' theory by making this small change to the source above:
alien = new BufferedImage(40, 40, BufferedImage.TYPE_INT_RGB);
//Toolkit.getDefaultToolkit().getImage("alien.png");
Given I saw an animated black square, it supports the major problem is that the image is not being found. The code still has a few other aspects that should be tweaked, but it is basically going in the right direction.
I have this png file and converted it to jpg image.
As you can see, some pixels around the circles are not as smooth as the circles in the png image.
I have this code to convert png to jpeg. How do I update the code so that I can remove the noise around the circles.
BufferedImage bufferedJpgImage = new BufferedImage(inputPngImage.getWidth(null),
inputPngImage.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(inputPngImage, 0, 0, bufferedJpgImage.getWidth(), bufferedJpgImage.getHeight(), Color.WHITE, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bufferedJpgImage, "jpg", out);
Jpeg uses a lossy compression algorithm, this means that the physical image data is modified in order to reduce the image size.
You can set the compression level through ImageIO, it's a little messy, but it should provide you the control you need.
So based the answer from Setting jpg compression level with ImageIO in Java, you could do something like:
The left is the original BufferedImage and the right is the resulting JPEG
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.spi.ServiceRegistry;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
try {
BufferedImage original = ImageIO.read(...);
BufferedImage bufferedJpgImage = new BufferedImage(original.getWidth(null),
original.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedJpgImage.createGraphics();
g.drawImage(original, 0, 0, original.getWidth(), original.getHeight(), Color.WHITE, null);
g.dispose();
File jpg = new File("tmp.jpg");
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
write(bufferedJpgImage, baos);
try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
BufferedImage image = ImageIO.read(bais);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(original)));
panel.add(new JLabel(new ImageIcon(image)));
JOptionPane.showMessageDialog(null, panel);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void write(BufferedImage capture, OutputStream to) throws IOException {
// use IIORegistry to get the available services
IIORegistry registry = IIORegistry.getDefaultInstance();
// return an iterator for the available ImageWriterSpi for jpeg images
Iterator<ImageWriterSpi> services = registry.getServiceProviders(ImageWriterSpi.class,
new ServiceRegistry.Filter() {
#Override
public boolean filter(Object provider) {
if (!(provider instanceof ImageWriterSpi)) {
return false;
}
ImageWriterSpi writerSPI = (ImageWriterSpi) provider;
String[] formatNames = writerSPI.getFormatNames();
for (int i = 0; i < formatNames.length; i++) {
if (formatNames[i].equalsIgnoreCase("JPEG")) {
return true;
}
}
return false;
}
},
true);
//...assuming that servies.hasNext() == true, I get the first available service.
ImageWriterSpi writerSpi = services.next();
ImageWriter writer = writerSpi.createWriterInstance();
// specifies where the jpg image has to be written
writer.setOutput(ImageIO.createImageOutputStream(to));
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
// writes the file with given compression level
// from your JPEGImageWriteParam instance
writer.write(null, new IIOImage(capture, null, null), jpegParams);
}
}
You need to make sure you're managing your resources properly, closing or disposing of them when you have finished with them
What you are seeing is a natural consequence of JPEG compression in non-photographic images. JPEG relies on people not being able to notice small graduations in photographic images. When there is an abrupt change from one color to another, you get the artifacts you see.
You can reduce this effect by quantization table selection (quality settings in most encoders) and not sampling the Cb and Cr components at a lower rate than Y.
However, for an image like what you are showing, you are better off sticking with PNG.
i need to ask if there are a way ( applet or any think else ) to take a screenshot of the content on a div in webpage ???
i found this java code to take screenshot of the full screen :
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ScreenShot
{
/**
method to capture screen shot
#param String uploadPath to save screen shot as image
#returns boolean true if capture successful else false
*/
boolean captureScreenShot(String uploadPath)
{
boolean isSuccesful = false;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture;
try
{
capture = new Robot().createScreenCapture(screenRect);
// screen shot image will be save at given path with name "screen.jpeg"
ImageIO.write(capture, "jpg", new File( uploadPath, "screen.jpeg"));
isSuccesful = true;
}
catch (AWTException awte)
{
awte.printStackTrace();
isSuccesful = false;
}
catch (IOException ioe)
{
ioe.printStackTrace();
isSuccesful = false;
}
return isSuccesful;
}
}
thanks
This is similar to the following question: Take a screenshot of a web page in Java
I need to get the background image from a PowerPoint slide using java. I am aware of the Apache POI project. I can find material for getting text and shapes from the slides, but not the actual background. Does anyone have any suggestions?
EDIT: I have creaked the following code using the suggested link. This code seems to grab the contents of the slide, but not exactly the background. The resulting images are white for the background.
I tried it with this PowerPoint
package PowerPointProcessing;
import Logging.LogRunner;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.model.Background;
import org.apache.poi.hslf.model.Fill;
import org.apache.poi.hslf.model.Shape;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
/**
*
* #author dvargo
*/
public class PPI
{
Dimension pageSize;
public Slide[] theSlides;
public PPI(String powerPointFilePath)
{
SlideShow ppt = null;
//open the presentation
try
{
ppt = new SlideShow(new HSLFSlideShow(powerPointFilePath));
}
catch(Exception e)
{
LogRunner.getLogger().severe("Could not open the powerpoint presentation");
return;
}
//get all the slides
theSlides = ppt.getSlides();
//see how many slides there are
int numberOfSlides = theSlides.length;
pageSize = ppt.getPageSize();
}
public BufferedImage getBackground(Slide theSlide)
{
Background background;
background = theSlide.getBackground();
Fill f = background.getFill();
Color color = f.getForegroundColor();
Shape[] theShapes = theSlide.getShapes();
BufferedImage img = new BufferedImage(pageSize.width, pageSize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setPaint(color);
graphics.fill(new Rectangle2D.Float(0, 0, pageSize.width, pageSize.height));
theSlide.draw(graphics);
return img;
}
public static void main(String[] args) {
PPI ppi = new PPI("C:\\Documents and Settings\\dvargo\\Desktop\\Cludder\\a.ppt");
int count= 0;
for (Slide currSlide : ppi.theSlides)
{
BufferedImage img = ppi.getBackground(currSlide);
try
{
ImageIO.write(img, "jpeg", new File("C:\\Documents and Settings\\dvargo\\Desktop\\ppt\\" + count + ".jpeg"));
}
catch (IOException ex)
{
Logger.getLogger(PPI.class.getName()).log(Level.SEVERE, null, ex);
}
count++;
}
}
}
Looking at the code from this question:
Extracting images from pptx with apache poi
Looks like it should be something like:
Background background = slides[current].getBackground();
Fill f = background.getFill();
Color color = f.getForegroundColor();