How to read OS X *.icns file with Java - java

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

Related

cvSaveImage() save image to a specific directory

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);

How to grab only selected components image while capturing the JPanel?

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

OpenCV not working correctly on mac

I have a program that uses OpenCV to take a picture using your webcam. It works like a charm on windows, yet, it doesn't work on OSx. The Frame where the Webcam view should appear stays empty. And when I take a picture, it just shows a black void, as if it couldnt find the webcam
public void run(){
try {
grabber = new VideoInputFrameGrabber(0);
grabber.start();
while (active) {
IplImage originalImage = grabber.grab();
Label.setIcon(new ImageIcon( originalImage.getBufferedImage() ));
}
grabber.stop();
grabber.flush();
} catch (Exception ex) {
//Logger.getLogger(ChPanel.class.getName()).log(Leve l.SEVERE, null, ex);
}
}
public BufferedImage saveImage(){
IplImage img;
try {
//capture image
img = grabber.grab();
// save to file
File outputfile = new File(Project.getInstance().getFileURLStr() + " capture" + fotoCount++ + ".jpg");
ImageIO.write(img.getBufferedImage(), "jpg", outputfile);
//get file and set it in the project library
BufferedImage ImportFile = ImageIO.read(outputfile);
Project p = Project.getInstance();
MainScreen ms = MainScreen.getInstance();
ImageIcon takenPhoto = new ImageIcon(ImportFile);
p.setNextImage(takenPhoto);
ms.setPanels();
return ImportFile;
} catch (com.googlecode.javacv.FrameGrabber.Exception e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Does anyone know how to solve this? I suspect something about rights to use the webcam or something like that
grabber = new VideoInputFrameGrabber(0);
Here 0 is specified for Capture device number 0
May be the number 0th device is not available for video capture
Use this code to get the list of devices and number respectively.
import com.googlecode.javacv.cpp.videoInputLib.videoInput;
class Main {
public static void main(String[] args) {
int n=videoInput.listDevices();
for(int i=0;i<n;i++)
{
System.out.println(i+" = "+videoInput.getDeviceName(i));
}
}
}
And then specify the number for that device
grabber = new VideoInputFrameGrabber(1); // 0 or 1 or 2
To interact with webcam I use this library webcam-capture you can easely add openCV dependency with maven. This is a great library

SWT UI Thread is not Responding - Printing Error

I have a Print Button in my SWT TitleAreaDialog.
viewPDFButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
try {
startPdfPrintOperation();
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
I am getting a existing PDF filename and path from a user selection from a table.
I am then wantinf to print the pdf file out to a local printer. The user needs to be allowed to select the local printer of choice.
public void startPdfPrintOperation() throws Exception {
File file = new File(getPDFFileName());
RandomAccessFile raf;
raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
pdfFile = new PDFFile(buf);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
// Create Print Job
pjob = PrinterJob.getPrinterJob();
pjob.setPrintable(new MyPrintable());
final HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (pjob.printDialog (attset)) {
try {
pjob.print (attset);
}
catch (PrinterException e) {
e.printStackTrace();
}
}
}
class MyPrintable implements Printable {
public int print (Graphics g, PageFormat format, int index) throws PrinterException {
int pagenum = index+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) g;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) format.getImageableWidth (),
(int) format.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) format.getImageableX (),
(int) format.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) g, bounds, null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
MessageDialog.openError(null, "PDF Error Message", "Needs");
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (format.getImageableX (),
format.getImageableY (),
format.getImageableWidth (),
format.getImageableHeight ()));
return PAGE_EXISTS;
}
}
I am getting the above error from line 315
if (pjob.printDialog (attset)) {
The printer dialog opens the entire application is frozen and goes unresponsive. Then in about 30 secs, I get the above error.
I have tried to use Display.getDefault().asyncExec(new Runnable() ) in multiple spots but that did not help.
Could it be because the base dialog is SWT and the printer dialog is AWT?
Since you didn't define "in multiple spots", I would suggest you refactor the print job in its own class, extends Thread and implement starting the print job in the run method.
I'm not familiar with all classes in above code, you can try simply starting this thread and it will run in parallel with the SWT thread. Try avoiding shared ressources, this may help resolving your deadlock. If you want to have a UI response from this thread, you can wrap e.g. the SWT messagebox ("Printing done!") in a call to Display.getDefault().asyncExec(new Runnable() { ... }.
Furthermore, please test if the printing code without UI code produces the same exception. If it does, the environment may be misconfigured.

Does anyone know how to display a BitmapField?

I have a code that encode a image to bitmap. But I am not sure on how to display it on the screen. By the way, I am using Blackberry JavaME. This is the code where i use to encode the image. Is this the way I can use in order to get image from a sd card and display it on the screen?
FileConnection conn =
(FileConnection)Connector.open("image1.png",Connector.READ_WRITE);
if(conn.exists()) {
InputStream is = conn.openInputStream();
BitmapField bitmap = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
{
baos.write(ch);
}
byte imageData[] = baos.toByteArray();
bitmap = new BitmapField(
EncodedImage.createEncodedImage(imageData, 0, imageData.length).getBitmap());
add(bitmap);
}
Secko is correct that you can override paint but I think you are getting stuck because you have not created a ui application.
Here is a very simple ui application example for displaying a bitmap field, if you copy it exactly you will need an images folder under src with image.png inside of it.
This was modified from the HelloWorldDemo that comes with the SDK. I recommend that if you are just starting out you look at the samples in the folder.
\plugins\net.rim.ejde.componentpack5.0.0_5.0.0.25\components\samples\
good luck
Ray
public class DisplayBitmaps extends UiApplication
{
public static void main(String[] args)
{
DisplayBitmaps theApp = new DisplayBitmaps();
theApp.enterEventDispatcher();
}
public DisplayBitmaps()
{
pushScreen(new DisplayBitmapsScreen());
}
}
final class DisplayBitmapsScreen extends MainScreen
{
DisplayBitmapsScreen()
{
Bitmap bitmap = EncodedImage.getEncodedImageResource("images/image.png").getBitmap();
BitmapField bitmapField = new BitmapField(bitmap);
add(bitmapField);
}
public void close()
{
super.close();
}
}
Edit for when the image is on the sdcard
DisplayBitmapsScreen()
{
//Bitmap bitmap = EncodedImage.getEncodedImageResource("images/image.png").getBitmap();
try {
FileConnection fc = (FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/image.png");
if (fc.exists()) {
byte[] image = new byte[(int) fc.fileSize()];
InputStream inStream = fc.openInputStream();
inStream.read(image);
inStream.close();
EncodedImage encodedImage = EncodedImage.createEncodedImage(image, 0, -1);
BitmapField bitmapField = new BitmapField(encodedImage.getBitmap());
fc.close();
add(bitmapField);
}
} catch (Exception e) { System.out.println("EXCEPTION " + e); }
}
Overriding paint in Field or any extension Field class could also display an image, but I didn't really understand from Secko's example where he would display the image so I have included drawImage in this example below.
protected void paint(Graphics graphics) {
graphics.drawImage(x, y, width, height, image, frameIndex, left, top);
super.paint(graphics);
}
You can do it with:
paint(Graphics g);
Perhaps in a function:
protected void DrawStuff(Graphics g) {
this.paint(g);
}

Categories

Resources