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);
}
Related
I am using a combination of PDFBox with Apache Batik in order to render PDF pages as SVG documents. Most of them work fine, but I have some issues when rendering specific images into SVG.
This is the code I use. It is mostly based on the post over there.
public void extractBookSvg(File pdfFile) throws Exception {
// ... preliminary business actions
SVGGeneratorContext ctx = createContext();
SVGGraphics2D g = null;
try (PDDocument document = PDDocument.load(pdfFile, MemoryUsageSetting.setupMixed(2147483648l))) {
PDFRenderer renderer = new PDFRenderer(document);
long startTime = System.currentTimeMillis();
int pageNr = 0;
for (PDPage page : document.getPages()) {
long startTimeForPage = System.currentTimeMillis();
g = createGraphics(ctx);
renderer.renderPageToGraphics(pageNr, g, 3.47222f);
pageNr++;
try (OutputStream os = new ByteArrayOutputStream();
Writer out = new OutputStreamWriter(os)) {
g.stream(out, true);
//... do other business actions
}
}
}
finally {
pdfFile.delete();
if (g != null) {
g.finalize();
g.dispose();
}
}
}
private SVGGraphics2D createGraphics(SVGGeneratorContext ctx) {
SVGGraphics2D g2d = new CustomSVGGraphics2D(ctx, false);
return g2d;
}
private SVGGeneratorContext createContext() {
DOMImplementation impl = GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document myFactory = impl.createDocument(svgNS, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
return ctx;
}
public static class CustomSVGGraphics2D extends SVGGraphics2D {
public CustomSVGGraphics2D(SVGGeneratorContext generatorCtx, boolean textAsShapes) {
super(generatorCtx, textAsShapes);
}
#Override
public GraphicsConfiguration getDeviceConfiguration() {
return new CustomGraphicsConfiguration();
}
}
private static final class CustomGraphicsConfiguration extends GraphicsConfiguration {
#Override
public AffineTransform getNormalizingTransform() {
return null;
}
#Override
public GraphicsDevice getDevice() {
return new CustomGraphicsDevice();
}
#Override
public AffineTransform getDefaultTransform() {
return null;
}
#Override
public ColorModel getColorModel(int transparency) {
return null;
}
#Override
public ColorModel getColorModel() {
return null;
}
#Override
public java.awt.Rectangle getBounds() {
return null;
}
}
private static final class CustomGraphicsDevice extends GraphicsDevice {
#Override
public int getType() {
return 0;
}
#Override
public String getIDstring() {
return null;
}
#Override
public GraphicsConfiguration[] getConfigurations() {
return null;
}
#Override
public GraphicsConfiguration getDefaultConfiguration() {
return null;
}
}
As mentioned above, the issue comes when rendering images: they either do not get rendered at all (show up as black boxes), or on some images that have opacity lower than 1, they are shown with opacity 1.
Here is an example of both cases:
PDF render of transparent image
SVG render of transparent image
These images do not get rendered at all in SVG
How they actually show in the SVG
However, if I directly render those pages as images (using BufferedImage instead Graphics2D), they both render fine (with a lower quality than the svg, of course).
Also, I have tried debugging the PDF with the PDFDebugger utility, and those images do not appear in the resources XObject list of the page, and I can't seem to find them nowhere else.
My questions are:
how can I find out if the issue comes from the way PDFBox renders into the Graphics2D object, or it comes from the way Batik does the SVG generation?
is there a way to make sure those images are properly displayed at generation time? Because I see no errors in the logs.
if so, what could be the solution?
Thank you!
Apparently, this is my code I have been using to get image from my disks to my program.
public void getVehicleImage(){
FileDialog fd = new FileDialog(this);
fd.setFile("*.jpg; *.jpg; *.png; *.gif");
fd.show();
vehicle_path = fd.getDirectory()+fd.getFile();
vehicleFileName.setText(vehicle_path = fd.getFile());
vehicleImagePath.setText(vehicle_path = fd.getDirectory()+fd.getFile());
image.setIcon(new ImageIcon(vehicle_path));
}
How do I fit the image to the size of my jLabel? I have tried using the
getScaledInstance()
but still no good. And also I want to ask if I am using the right code on how to get Image from my disk? I kinda feel it is wrong.
I faced similar problem and did below workaround:
Step1: Read the picture as a BufferedImage from your file system.
BufferedImage image = null;
try {
image = ImageIO.read(new File("fileName.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Step2: Create a new BufferedImage that is the size of the JLabel
BufferedImage img= image.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
Step3: Create new ImageIcon from the resized BufferedImage (Step 2)
ImageIcon imageIcon = new ImageIcon(img);
In your case, create a helper method and call it while creating ImageIcon as below:
public void getVehicleImage(){
...................
image.setIcon(new ImageIcon(getScaledImage(vehicle_path)));//call helper here
}
This can be helper function:
public BufferedImage getScaledImage(String imagePath){
BufferedImage image = null;
try {
image = ImageIO.read(new File("fileName.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage img= image.getScaledInstance(label.width, label.height,
Image.SCALE_SMOOTH);
return img;
}
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
I know we can simulate the print screen with the following code:
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
..but then how to return some BufferedImage?
I found on Google some method called getClipboard() but Netbeans return me some error on this one (cannot find symbol).
I am sorry to ask this, but could someone show me a working code on how returning from this key press a BufferedImage that I could then save?
This won't necessarily give you a BufferedImage, but it will be an Image. This utilizes Toolkit.getSystemClipboard.
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) {
final Image screenshot = (Image) clipboard.getData(DataFlavor.imageFlavor);
...
}
If you really need a BufferedImage, try as follows...
final GraphicsConfiguration config
= GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage copy = config.createCompatibleImage(
screenshot.getWidth(null), screenshot.getHeight(null));
final Object monitor = new Object();
final ImageObserver observer = new ImageObserver() {
public void imageUpdate(final Image img, final int flags,
final int x, final int y, final int width, final int height) {
if ((flags & ALLBITS) == ALLBITS) {
synchronized (monitor) {
monitor.notifyAll();
}
}
}
};
if (!copy.getGraphics().drawImage(screenshot, 0, 0, observer)) {
synchronized (monitor) {
try {
monitor.wait();
} catch (final InterruptedException ex) { }
}
}
Though, I'd really have to ask why you don't just use Robot.createScreenCapture.
final Robot robot = new Robot();
final GraphicsConfiguration config
= GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
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