JPanel with 3 JButton and I need only two of them to be captured...
public static void grabScreenShot(JPanel panel) {
BufferedImage image = (BufferedImage) panel.createImage(
panel.getSize().width, panel.getSize().height);
panel.paint(image.getGraphics());
File file = null;
file = new File("Customers");
if (!file.exists()) {
file.mkdir();
}
try {
file = new File("Customers" + File.separator
+ String.valueOf(System.currentTimeMillis()));
ImageIO.write(image, "png", file);
System.out.println("Image was created");
} catch (IOException e) {
System.out.println("Had trouble writing the image.");
e.printStackTrace();
}
}
How to avoid unnecessary components to be captured.?
You can try to override paintComponent() of the buttons and introduce a flag needPaint. The flag is true by default.
if (needPaint) {
super.paintComponent(g);
}
In your grabScreenShot() set the flag to false for the button to be hidden and reset it back after panel.paint(image.getGraphics()); call
Related
I'm using JavaCV. My program required to make a webcam photo and save it to the folder which is on the desktop.
Here is the path to the folder :
public static String webcamPath = System.getProperty("user.home") + "/Desktop/folder/webcam.png"
That is how i save the image :
FrameGrabber grabber = new VideoInputFrameGrabber(0);
try {
grabber.start();
Thread.sleep(1000);
while (true) {
IplImage img = grabber.grab();
if (img != null) {
cvSaveImage(webcamPath, img);
grabber.stop();
}
}
} catch (Exception e) {
e.printStackTrace();
}
But when the webcam starts working, it can't save the image and i'm getting this exception :
com.googlecode.javacv.FrameGrabber$Exception: videoInput is null. (Has start() been called?)
So is there any way to save the IplImage to a folder on the desktop?
Thanks.
In your code, this is the flow:
start the FrameGrabber
start loop
grab
stop the grabber
trying to grab again <<< exception occurs because grabber is not opened again
My guess is to place the open inside the loop:
FrameGrabber grabber = new VideoInputFrameGrabber(0);
try {
while (true) {
grabber.start();
Thread.sleep(1000);
IplImage img = grabber.grab();
if (img != null) {
cvSaveImage(webcamPath, img);
grabber.stop();
}
}
} catch (Exception e) {
e.printStackTrace();
}
Save your file to specific directory by adding:
cvSaveImage(<path>\\<imagename>, img);
I would like to use an image as the background of a JPanel.
It needs to be loaded from a relative file path.
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JLabel background = new JLabel(new ImageIcon(backgroundImage));
this.add(background);
} catch(IOException e) {
System.out.println(e.toString());
}
}
My current code is not working. Any help would be appreciated.
So can't comment(need 50 rep) but your file path is completely wrong
you need it to be something like this
new File("C:/Users/"Insert Username"/Desktop/workspace/Java/BSC_Project/Application/src/resources/background.jpg")
except I'm not on your computer so you need to figure out your own file path, This would be assuming your workspace folder is on your Desktop which it almost certainly isn't, do you understand?
Well if you want your code to have a panel this is what you would do...
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JPanel panel = new JPanel();
JLabel background = new JLabel(new ImageIcon(backgroundImage));
panel.add(background);
this.add(panel);
} catch(IOException e) {
System.out.println(e.toString());
}
}
but in your case it looks to me like you want a frame background as image... to which you can set the image background to which for that one you can try this code
JFrame f = new JFrame ("SettingBackGround");
try{
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Med.jpg")))));
}catch (IOException e){
System.out.println("Image Doesnt Exist");
}
f.setVisible(true);
f.setResizable(false);
f.pack();
}
}
I hope this helps though.
public WelcomeView() {
initComponents();
try {
image = ImageIO.read(new File("C:\\Users\\Developer\\workspace\\Java\\BSC_Project\\Application\\src\\application\\resources\\background.png"));
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
private BufferedImage image;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 2, 0, null); // see javadoc for more info on the parameters
}
I have a weird problem,
I have an activity, within this activity I have a layout I want to make an image of it in order to share it on social networks.
This layout contains differents dynamic images and texts. That's why I can't just store it on as a static image and share it on demand. I need to generate the image right when the user touch the share button.
The problem is that I need to adjust the layout before sharing, what I do ?
ImageView profilPic = (ImageView)dashboardView.findViewById(R.id.profilePic);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)profilPic.getLayoutParams();
params.setMargins(10, 62, 0, 0);
profilPic.invalidate();
profilPic.requestLayout();
First I modify the margin of my layout, then I make an image of it
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(dashboardView.getWidth(),
dashboardView.getHeight(), Bitmap.Config.ARGB_4444);
dashboardView.draw(new Canvas(bitmap));
} catch (Exception e) {
// Logger.e(e.toString());
}
FileOutputStream fileOutputStream = null;
File path = Environment
.getExternalStorageDirectory();
File file = new File(path, "wayzupDashboard" + ".png");
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bitmap.compress(CompressFormat.PNG, 100, bos);
try {
bos.flush();
bos.close();
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
And finally I share it.
Basically it works, except that it captures the layout BEFORE redrawing the layout with modified layoutParams.
I need to capture this layout once and only when the new layout parameters are took into account, after layout is redraw.
If I remove the capture code, well it works, when I touch the share button I see the layout moving. But when I have the capture code in place it just capture the layout before modifying margins.
How can I ensure that the layout is redraw before capturing it ?
For the record, to correctly capture the layout only once the view was setup I needed to first setup the view and then capture the layout in a delayed thread. This is the only way I found to make it works.
public void onShareButton() {
dashboardController.setupViewBeforeSharing();
new Timer().schedule(new TimerTask() {
#Override
public void run() {
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(dashboardView.getWidth(),
dashboardView.getHeight(), Bitmap.Config.ARGB_4444);
dashboardView.draw(new Canvas(bitmap));
} catch (Exception e) {
// Logger.e(e.toString());
}
FileOutputStream fileOutputStream = null;
File path = Environment
.getExternalStorageDirectory();
File file = new File(path, "wayzupDashboard" + ".png");
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bitmap.compress(CompressFormat.PNG, 100, bos);
try {
bos.flush();
bos.close();
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
share.putExtra(Intent.EXTRA_TEXT, R.string.addPassengerButton);
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + file.getAbsolutePath()));
startActivity(Intent.createChooser(share, "Share image"));
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
dashboardController.setupViewAfterSharing();
}
});
}
}, 300);
}
An easier way, is to set-up a listener for layout pass on the dashboardView view.
Setting-up listener using View.addOnLayoutChangeListener() - addOnLayoutChangeListener.
Set the listener before changing the layout parameters and remove it after the image was saved to persistence.
Hope it'll add any improvement.
Why is the following bit of code returns Height: -1 which means that the height is yet not known. How to get height of the image?
try {
// Create a URL for the image's location
URL url = new URL("http://bmw-2006.auto-one.co.uk/wp-content/uploads/bmw-m3-2006-3.jpg");
// Get the image
java.awt.Image image = Toolkit.getDefaultToolkit().createImage(url);
System.out.println("Height: " + image.getHeight(null));
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Use ImageIO.read(URL) or ImageIO.read(File) instead. It will block while loading, and the image width & height will be known after it returns.
E.G.
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class SizeOfImage {
public static void main(String[] args) throws Exception {
URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
final BufferedImage bi = ImageIO.read(url);
final String size = bi.getWidth() + "x" + bi.getHeight();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel l = new JLabel(
size,
new ImageIcon(bi),
SwingConstants.RIGHT );
JOptionPane.showMessageDialog(null, l);
}
});
}
}
Alternately, add a MediaTracker to the image being loaded asynchronously by the Toolkit and wait until it is completely loaded.
You want something like this:
try {
// Create a URL for the image's location
URL url = new URL("http://bmw-2006.auto-one.co.uk/wp-content/uploads/bmw-m3-2006-3.jpg");
// Get the image
Image image = ImageIO.read(url);
System.out.println("Height: " + image.getHeight(null));
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
The java.awt.Toolkit approach won't block, so will return -1 and notify the observer (or not in your case because it's null) when it is loaded. If you do want it asynchronously then you'll need to provide a callback in the form of an image observer.
Oh, and don't just ignore exceptions, at least print the stack trace!
Because the image is loaded asynchronously, in the background.
As the getHeight() javadoc says, you need to provide an ImageObserver (instead of null), which is called when the image has been loaded.
Toolkit#createImage(...) is non-blocking. Generally I would rather use javax.imageio.ImageIOto read images.
To wait for the Toolkit#createImage(...), use:
MediaTracker mediaTracker = new MediaTracker(component);
mediaTracker.addImage(image);
try {
mediaTracker.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
After that, you can call image.getHeight()
createImage runs in background to load the Image.
use a MediaTracker to wait for the loading and then use getHeight (and use a valid ImageObserver to prevent errors)
I want to read *.icns files in OS X into a BufferedImage. Help
Try this: http://code.google.com/p/appengine-awt/source/browse/trunk/apache-sanselan/src/main/java/org/apache/sanselan/formats/icns/IcnsDecoder.java?spec=svn8&r=8
Which is actually from: http://incubator.apache.org/sanselan/site/index.html
You need to convert ICNS to another image type first, and after load this image you can delete it. This is how to convert PNG to ICNS, so you just need to do in the opposite way:
public static void Png(File png, File icns) throws IOException{
ImageIcon image = new ImageIcon(ImageIO.read(png));
ImageIconAs(image, icns);
}
public static void ImageIconAs(ImageIcon ii, File icns) throws IOException{IconAs((Icon)ii,icns);}
public static void IconAs(Icon icon, File icns) throws IOException{
if (icon != null) {
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB );
Graphics2D g = bi.createGraphics();
icon.paintIcon(new Canvas(), g, 0, 0 );
g.dispose();
File outputfile = new File("temp000.png");
ImageIO.write(bi, "png", outputfile);
execTerminal(new String[]{ "sips", "-s", "format", "tiff",
"temp000.png","--out", "temp000.tiff" });
File apaga2 = new File("temp000.png");
apaga2.delete();
execTerminal(new String[]{ "tiff2icns", "-noLarge",
"temp000.tiff", icns.getAbsolutePath()});
File apaga = new File("temp000.tiff");
apaga.delete();
}
}
static void execTerminal(String[] cmd){
int exitCode = 0;
try {
exitCode = Runtime.getRuntime().exec(cmd).waitFor();
}
catch (InterruptedException e) {e.printStackTrace();}
catch (IOException e) {
if (exitCode != 0) System.out.println("ln signaled an error with exit code " + exitCode);
}
}
You just need to use this to call the action:
Png(png_file,icns_file);
You can youse IconManager. It works with following icons formats:
*.ico - Windows Icon
*.icl - Windows Icon Library
*.icns - Macintosh Icon