Search Results

Search found 143 results on 6 pages for 'bufferedimage'.

Page 5/6 | < Previous Page | 1 2 3 4 5 6  | Next Page >

  • How to move image in Applet?

    - by user1609804
    I want to move the character left, right up, and down in applet, but it is not moving at all. here is my code, help please import javax.swing.JPanel; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import java.applet.*; import java.awt.event.*; import java.awt.*; public class drawCenter extends Applet { private int x,y;// the x and y of the position of the player private BufferedImage image, pos; public void init( ) { try { image = ImageIO.read(new File("pokemonCenter.png")); pos = ImageIO.read(new File("player/maleInGame.png")); } catch (IOException ex) { } x = 150; y = 171; } public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); switch( keyCode ) { case KeyEvent.VK_UP: if( y>0 ) { y=y-19; repaint(); } break; case KeyEvent.VK_DOWN: if( y<171 ) { y=y+19; repaint(); } break; case KeyEvent.VK_LEFT:if( x>0 ) { x=x-15; repaint(); } break; case KeyEvent.VK_RIGHT:if( x<285 ) { x=x+15; repaint(); } break; } e.consume(); } public void keyReleased(){ } public void paint( Graphics g ) { g.drawImage(image, 0, 0, null); g.drawImage(pos, x, y, null); } }

    Read the article

  • Getting problem in accessing web cam.

    - by Chetan
    Hi... I have written code in Java to access web cam,and to save image... I am getting following exceptions : Exception in thread "main" java.lang.NullPointerException at SwingCapture.(SwingCapture.java:40) at SwingCapture.main(SwingCapture.java:66) how to remove this exceptions. here is the code: import javax.swing.*; import javax.swing.event.; import java.io.; import javax.media.; import javax.media.format.; import javax.media.util.; import javax.media.control.; import javax.media.protocol.; import java.util.; import java.awt.; import java.awt.image.; import java.awt.event.; import com.sun.image.codec.jpeg.; public class SwingCapture extends Panel implements ActionListener { public static Player player = null; public CaptureDeviceInfo di = null; public MediaLocator ml = null; public JButton capture = null; public Buffer buf = null; public Image img = null; public VideoFormat vf = null; public BufferToImage btoi = null; public ImagePanel imgpanel = null; public SwingCapture() { setLayout(new BorderLayout()); setSize(320,550); imgpanel = new ImagePanel(); capture = new JButton("Capture"); capture.addActionListener(this); String str1 = "vfw:iNTEX IT-308 WC:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; di = CaptureDeviceManager.getDevice(str2); ml = di.getLocator(); try { player = Manager.createRealizedPlayer(ml); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { add(comp,BorderLayout.NORTH); } add(capture,BorderLayout.CENTER); add(imgpanel,BorderLayout.SOUTH); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Frame f = new Frame("SwingCapture"); SwingCapture cf = new SwingCapture(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { playerclose(); System.exit(0);}}); f.add("Center",cf); f.pack(); f.setSize(new Dimension(320,550)); f.setVisible(true); } public static void playerclose() { player.close(); player.deallocate(); } public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); if (c == capture) { // Grab a frame FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl"); buf = fgc.grabFrame(); // Convert it to an image btoi = new BufferToImage((VideoFormat)buf.getFormat()); img = btoi.createImage(buf); // show the image imgpanel.setImage(img); // save image saveJPG(img,"\test.jpg"); } } class ImagePanel extends Panel { public Image myimg = null; public ImagePanel() { setLayout(null); setSize(320,240); } public void setImage(Image img) { this.myimg = img; repaint(); } public void paint(Graphics g) { if (myimg != null) { g.drawImage(myimg, 0, 0, this); } } } public static void saveJPG(Image img, String s) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); FileOutputStream out = null; try { out = new FileOutputStream(s); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(0.5f,false); encoder.setJPEGEncodeParam(param); try { encoder.encode(bi); out.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } } }

    Read the article

  • JPanel Layout Image Cutoff

    - by Trizicus
    I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either. So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code. Custom JPanel: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel implements MouseListener { private Entity test; private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; GraphicsPanel() { test = new Entity("test.png"); Thread t1 = new Thread(test); t1.start(); Entity ent2 = new Entity("images.jpg"); ent2.setX(150); ent2.setY(150); Thread t2 = new Thread(ent2); t2.start(); Entity ent3 = new Entity("test.png"); ent3.setX(0); ent3.setY(150); Thread t3 = new Thread(ent3); t3.start(); //ESSENTIAL setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(test); add(ent2); add(ent3); //GAMELOOP timer = new Timer(30, new Gameloop(this)); timer.start(); addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } class Gameloop implements ActionListener { private GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { gp.getFPS(); gp.repaint(); } catch (Exception ez) { } } } } Main class: import java.awt.EventQueue; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } private JFrame frame; private GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gp); } }); } } Custom JComponent import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JComponent; public class Entity extends JComponent implements Runnable { private BufferedImage bImg; private int x = 0; private int y = 0; private int entityWidth, entityHeight; private String filename; Entity(String filename) { this.filename = filename; } public void run() { bImg = loadBImage(filename); entityWidth = bImg.getWidth(); entityHeight = bImg.getHeight(); setPreferredSize(new Dimension(entityWidth, entityHeight)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(bImg, x, y, null); g2d.dispose(); } public BufferedImage loadBImage(String filename) { try { bImg = ImageIO.read(getClass().getResource(filename)); } catch (Exception e) { } return bImg; } public int getEntityWidth() { return entityWidth; } public int getEntityHeight() { return entityHeight; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }

    Read the article

  • java code for capture the image by webcam

    - by Navneet
    I am using windows7 64 bit operating system. The source code is for capturing the image by webcam: import javax.swing.*; import javax.swing.event.*; import java.io.*; import javax.media.*; import javax.media.format.*; import javax.media.util.*; import javax.media.control.*; import javax.media.protocol.*; import java.util.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import com.sun.image.codec.jpeg.*; public class SwingCapture extends Panel implements ActionListener { public static Player player = null; public CaptureDeviceInfo di = null; public MediaLocator ml = null; public JButton capture = null; public Buffer buf = null; public Image img = null; public VideoFormat vf = null; public BufferToImage btoi = null; public ImagePanel imgpanel = null; public SwingCapture() { setLayout(new BorderLayout()); setSize(320,550); imgpanel = new ImagePanel(); capture = new JButton("Capture"); capture.addActionListener(this); String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; di = CaptureDeviceManager.getDevice(str2); ml = di.getLocator(); try { player = Manager.createRealizedPlayer(ml); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { add(comp,BorderLayout.NORTH); } add(capture,BorderLayout.CENTER); add(imgpanel,BorderLayout.SOUTH); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Frame f = new Frame("SwingCapture"); SwingCapture cf = new SwingCapture(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { playerclose(); System.exit(0);}}); f.add("Center",cf); f.pack(); f.setSize(new Dimension(320,550)); f.setVisible(true); } public static void playerclose() { player.close(); player.deallocate(); } public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); if (c == capture) { // Grab a frame FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl"); buf = fgc.grabFrame(); // Convert it to an image btoi = new BufferToImage((VideoFormat)buf.getFormat()); img = btoi.createImage(buf); // show the image imgpanel.setImage(img); // save image saveJPG(img,"c:\\test.jpg"); } } class ImagePanel extends Panel { public Image myimg = null; public ImagePanel() { setLayout(null); setSize(320,240); } public void setImage(Image img) { this.myimg = img; repaint(); } public void paint(Graphics g) { if (myimg != null) { g.drawImage(myimg, 0, 0, this); } } } public static void saveJPG(Image img, String s) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); FileOutputStream out = null; try { out = new FileOutputStream(s); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(0.5f,false); encoder.setJPEGEncodeParam(param); try { encoder.encode(bi); out.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } } } This code is sucessfully compiled. On running the code, the following runtime error occurs: Exception in thread "VFW Request Thread" java.lang.UnsatisfiedLinkError:JMFSecurityManager: java.lang.UnsatisfiedLinkError:no jmvfw in java.library.path at com.sun.media.JMFSecurityManager.loadLibrary(JMFSecurityManager.java:206) at com.sun.media.protocol.vfw.VFWCapture.<clinit><VFWCapture.java:19> at com.sun.media.protocol.vfw.VFWSourceStream.doConnect(VFWSourceStream.java:241) at com.sun.media.protocol.vfw.VFWSourceStream.run(VFWSourceStream.java:763) at java.cdlang.Thread.run(Thread.java:619) Please send me solution of this problem/

    Read the article

  • Why keylistener is not working here?

    - by swift
    i have implemented keylistener interface and implemented all the needed methods but when i press the key nothing happens here, why? package swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JTextArea; class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { static BufferedImage image; String shape; Color color=Color.black; Point start; Point end; Point mp; Button elipse=new Button("elipse"); int x[]=new int[50]; int y[]=new int[50]; Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[9]; String selected; Point label; String key; int ex,ey;//eraser //DatagramSocket dataSocket; JButton button = new JButton("test"); JLayeredPane layerpane; Point p=new Point(); int w,h; public Paper() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(640, 480); frame.setBackground(Color.black); layerpane=frame.getLayeredPane(); setWidth(539,444); setBounds(69,0,555,444); layerpane.add(this,new Integer(2)); layerpane.add(this.addButtons(),new Integer(0)); setLayout(null); setOpaque(false); addMouseListener(this); addMouseMotionListener(this); setFocusable(true); addKeyListener(this); System.out.println(isFocusable()); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) g2.drawPolygon(x,y,2); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) g2.drawPolygon(x,y,2); } if(label!=null) { JTextArea textarea=new JTextArea(); if(selected==("text")) { textarea.setBounds(label.x, label.y, 50, 50); textarea.setMaximumSize(new Dimension(100,100)); textarea.setBackground(new Color(237,237,237)); add(textarea); g2.drawString("key",label.x,label.y); } } start=null; repaint(); g2.dispose(); } public void text() { System.out.println(label); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x, start.y, 10, 10); } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); buttonpanel.setMaximumSize(new Dimension(70,70)); JPanel shape=new JPanel(); JPanel colourbox=new JPanel(); shape.setLayout(new GridLayout(4,2)); shape.setMaximumSize(new Dimension(70,140)); colourbox.setLayout(new GridLayout(3,3)); colourbox.setMaximumSize(new Dimension(70,70)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round rect"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); shape.add(elipse); shape.add(rectangle); shape.add(line); shape.add(erase); shape.add(roundrect); shape.add(polygon); shape.add(text); buttonpanel.add(shape); for(int i=0;i<9;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); colourbutton[i].addActionListener(this); } buttonpanel.add(colourbox); buttonpanel.setBounds(0, 0, 70, 210); return buttonpanel; } public void mouseClicked(MouseEvent e) { if(selected=="text") { label=new Point(); label=e.getPoint(); draw(); } } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase"||selected=="text") { start=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { mp = e.getPoint(); } else if(selected=="poly") { x[0]=e.getX(); y[0]=e.getY(); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } draw(); } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); } else if(selected=="erase") { start=e.getPoint(); erase(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); } else if(selected=="poly") { x[1]=e.getX(); y[1]=e.getY(); } repaint(); } public void mouseMoved(MouseEvent arg0) {} public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) selected="poly"; else if(e.getSource()==text) selected="text"; if(e.getSource()==colourbutton[0]) color=Color.black; else if(e.getSource()==colourbutton[1]) color=Color.white; else if(e.getSource()==colourbutton[2]) color=Color.red; else if(e.getSource()==colourbutton[3]) color=Color.orange; else if(e.getSource()==colourbutton[4]) color=Color.blue; else if(e.getSource()==colourbutton[5]) color=Color.green; else if(e.getSource()==colourbutton[6]) color=Color.pink; else if(e.getSource()==colourbutton[7]) color=Color.magenta; else if(e.getSource()==colourbutton[8]) color=Color.cyan; } @Override public void keyPressed(KeyEvent e) { System.out.println("pressed"); } @Override public void keyReleased(KeyEvent e) { System.out.println("key released"); } @Override public void keyTyped(KeyEvent e) { System.out.println("Typed"); } public static void main(String[] a) { new Paper(); } } class Button extends JButton { String name; public Button(String name) { this.name=name; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",5, 22); } }

    Read the article

  • Java Port Socket Programming Error

    - by atrus-darkstone
    Hi- I have been working on a java client-server program using port sockets. The goal of this program is for the client to take a screenshot of the machine it is running on, break the RGB info of this image down into integers and arrays, then send this info over to the server, where it is reconstructed into a new image file. However, when I run the program I am experiencing the following two bugs: The first number recieved by the server, no matter what its value is according to the client, is always 49. The client only sends(or the server only receives?) the first value, then the program hangs forever. Any ideas as to why this is happening, and what I can do to fix it? The code for both client and server is below. Thanks! CLIENT: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.*; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ViewerClient implements ActionListener{ private Socket vSocket; private BufferedReader in; private PrintWriter out; private Robot robot; // static BufferedReader orders = null; public ViewerClient() throws Exception{ vSocket = null; in = null; out = null; robot = null; } public void setVSocket(Socket vs) { vSocket = vs; } public void setInput(BufferedReader i) { in = i; } public void setOutput(PrintWriter o) { out = o; } public void setRobot(Robot r) { robot = r; } /*************************************************/ public Socket getVSocket() { return vSocket; } public BufferedReader getInput() { return in; } public PrintWriter getOutput() { return out; } public Robot getRobot() { return robot; } public void run() throws Exception{ int speed = 2500; int pause = 5000; Timer timer = new Timer(speed, this); timer.setInitialDelay(pause); // System.out.println("CLIENT: Set up timer."); try { setVSocket(new Socket("Alex-PC", 4444)); setInput(new BufferedReader(new InputStreamReader(getVSocket().getInputStream()))); setOutput(new PrintWriter(getVSocket().getOutputStream(), true)); setRobot(new Robot()); // System.out.println("CLIENT: Established connection and IO ports."); // timer.start(); captureScreen(nameImage()); }catch(Exception e) { System.err.println(e); } } public void captureScreen(String fileName) throws Exception{ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize); BufferedImage image = getRobot().createScreenCapture(screenRectangle); int width = image.getWidth(); int height = image.getHeight(); int[] pixelData = new int[(width * height)]; image.getRGB(0,0, width, height, pixelData, width, height); byte[] imageData = new byte[(width * height)]; String fromServer = null; if((fromServer = getInput().readLine()).equals("READY")) { sendWidth(width); sendHeight(height); sendArrayLength((width * height)); sendImageInfo(fileName); sendImageData(imageData); } /* System.out.println(imageData.length); String fromServer = null; for(int i = 0; i < pixelData.length; i++) { imageData[i] = ((byte)pixelData[i]); } System.out.println("CLIENT: Pixel data successfully converted to byte data."); System.out.println("CLIENT: Waiting for ready message..."); if((fromServer = getInput().readLine()).equals("READY")) { System.out.println("CLIENT: Ready message recieved."); getOutput().println("SENDING ARRAY LENGTH..."); System.out.println("CLIENT: Sending array length..."); System.out.println("CLIENT: " + imageData.length); getOutput().println(imageData.length); System.out.println("CLIENT: Array length sent."); getOutput().println("SENDING IMAGE..."); System.out.println("CLIENT: Sending image data..."); for(int i = 0; i < imageData.length; i++) { getOutput().println(imageData[i]); } System.out.println("CLIENT: Image data sent."); getOutput().println("SENDING IMAGE WIDTH..."); System.out.println("CLIENT: Sending image width..."); getOutput().println(width); System.out.println("CLIENT: Image width sent."); getOutput().println("SENDING IMAGE HEIGHT..."); System.out.println("CLIENT: Sending image height..."); getOutput().println(height); System.out.println("CLIENT: Image height sent..."); getOutput().println("SENDING IMAGE INFO..."); System.out.println("CLIENT: Sending image info..."); getOutput().println(fileName); System.out.println("CLIENT: Image info sent."); getOutput().println("FINISHED."); System.out.println("Image data sent successfully."); } if((fromServer = getInput().readLine()).equals("CLOSE DOWN")) { getOutput().close(); getInput().close(); getVSocket().close(); } */ } public String nameImage() throws Exception { String dateFormat = "yyyy-MM-dd HH-mm-ss"; Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); String fileName = sdf.format(cal.getTime()); return fileName; } public void sendArrayLength(int length) throws Exception { getOutput().println("SENDING ARRAY LENGTH..."); getOutput().println(length); } public void sendWidth(int width) throws Exception { getOutput().println("SENDING IMAGE WIDTH..."); getOutput().println(width); } public void sendHeight(int height) throws Exception { getOutput().println("SENDING IMAGE HEIGHT..."); getOutput().println(height); } public void sendImageData(byte[] imageData) throws Exception { getOutput().println("SENDING IMAGE..."); for(int i = 0; i < imageData.length; i++) { getOutput().println(imageData[i]); } } public void sendImageInfo(String info) throws Exception { getOutput().println("SENDING IMAGE INFO..."); getOutput().println(info); } public void actionPerformed(ActionEvent a){ String message = null; try { if((message = getInput().readLine()).equals("PROCESSING...")) { if((message = getInput().readLine()).equals("IMAGE RECIEVED SUCCESSFULLY.")) { captureScreen(nameImage()); } } }catch(Exception e) { JOptionPane.showMessageDialog(null, "Problem: " + e); } } } SERVER: import java.awt.image.BufferedImage; import java.io.*; import java.net.*; import javax.imageio.ImageIO; /*IMPORTANT TODO: * 1. CLOSE ALL STREAMS AND SOCKETS WITHIN CLIENT AND SERVER! * 2. PLACE MAIN EXEC CODE IN A TIMED WHILE LOOP TO SEND FILE EVERY X SECONDS * */ public class ViewerServer { private ServerSocket vServer; private Socket vClient; private PrintWriter out; private BufferedReader in; private byte[] imageData; private int width; private int height; private String imageInfo; private int[] rgbData; private boolean active; public ViewerServer() throws Exception{ vServer = null; vClient = null; out = null; in = null; imageData = null; width = 0; height = 0; imageInfo = null; rgbData = null; active = true; } public void setVServer(ServerSocket vs) { vServer = vs; } public void setVClient(Socket vc) { vClient = vc; } public void setOutput(PrintWriter o) { out = o; } public void setInput(BufferedReader i) { in = i; } public void setImageData(byte[] imDat) { imageData = imDat; } public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } public void setImageInfo(String im) { imageInfo = im; } public void setRGBData(int[] rd) { rgbData = rd; } public void setActive(boolean a) { active = a; } /***********************************************/ public ServerSocket getVServer() { return vServer; } public Socket getVClient() { return vClient; } public PrintWriter getOutput() { return out; } public BufferedReader getInput() { return in; } public byte[] getImageData() { return imageData; } public int getWidth() { return width; } public int getHeight() { return height; } public String getImageInfo() { return imageInfo; } public int[] getRGBData() { return rgbData; } public boolean getActive() { return active; } public void run() throws Exception{ connect(); setActive(true); while(getActive()) { recieve(); } close(); } public void recieve() throws Exception{ String clientStatus = null; int clientData = 0; // System.out.println("SERVER: Sending ready message..."); getOutput().println("READY"); // System.out.println("SERVER: Ready message sent."); if((clientStatus = getInput().readLine()).equals("SENDING IMAGE WIDTH...")) { setWidth(getInput().read()); System.out.println("Width: " + getWidth()); } if((clientStatus = getInput().readLine()).equals("SENDING IMAGE HEIGHT...")) { setHeight(getInput().read()); System.out.println("Height: " + getHeight()); } if((clientStatus = getInput().readLine()).equals("SENDING ARRAY LENGTH...")) { clientData = getInput().read(); setImageData(new byte[clientData]); System.out.println("Array length: " + clientData); } if((clientStatus = getInput().readLine()).equals("SENDING IMAGE INFO...")) { setImageInfo(getInput().readLine()); System.out.println("Image Info: " + getImageInfo()); } if((clientStatus = getInput().readLine()).equals("SENDING IMAGE...")) { for(int i = 0; i < getImageData().length; i++) { getImageData()[i] = ((byte)getInput().read()); } } if((clientStatus = getInput().readLine()).equals("FINISHED.")) { getOutput().println("PROCESSING..."); setRGBData(new int[getImageData().length]); for(int i = 0; i < getRGBData().length; i++) { getRGBData()[i] = getImageData()[i]; } BufferedImage image = null; image.setRGB(0, 0, getWidth(), getHeight(), getRGBData(), getWidth(), getHeight()); ImageIO.write(image, "png", new File(imageInfo + ".png")); //create an image file out of the screenshot getOutput().println("IMAGE RECIEVED SUCCESSFULLY."); } } public void connect() throws Exception { setVServer(new ServerSocket(4444)); //establish server connection // System.out.println("SERVER: Connection established."); setVClient(getVServer().accept()); //accept client connection request // System.out.println("SERVER: Accepted connection request."); setOutput(new PrintWriter(vClient.getOutputStream(), true)); //set up an output channel setInput(new BufferedReader(new InputStreamReader(vClient.getInputStream()))); //set up an input channel // System.out.println("SERVER: Created IO ports."); } public void close() throws Exception { getOutput().close(); getInput().close(); getVClient().close(); getVServer().close(); } }

    Read the article

  • RGB values from image into a one dimension array in c#

    - by velocityxyz
    I was wondering if there is a was a way to read rgb values from an image into a one dimensional array in C#. If it doesnt make sense, in java I would do something like this. int[] pixels; BufferedImage image = getClass().getResourceAsStream("asdfghjkl.png"); int w = image.getWidth(); int h = image.getHeight(); pixels = new int[w * h]; image.getRGB(0, 0, w, h, pixels, 0, w) ; So any help would be great, or if you can point me in the right direction, that'd be great

    Read the article

  • Using a Higher Precision (than 8-bit unsigned integer) Buffered Image for Heightmaps in Java

    - by pl12
    I am generating a heightmap for every quad in my quadtree in openCL. The way I was creating the image is as follows: DataBufferInt dataBuffer = (DataBufferInt)img.getRaster().getDataBuffer(); int data[] = dataBuffer.getData(); //img is a bufferedimage inputImageMem = CL.clCreateImage2D( context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, new cl_image_format[]{imageFormat}, size, size, size * Sizeof.cl_uint, Pointer.to(data), null); This works ok but the major issue is that as the quads get smaller and smaller the 8-bit format of the buffered image starts to cause intolerable "stepping" issues as seen below: I was wondering if there was an alternate way I could go about doing this? Thanks for the time.

    Read the article

  • java.lang.Error: "Not enough storage is available to process this command" when generating images

    - by jhericks
    I am running a web application on BEA Weblogic 9.2. Until recently, we were using JDK 1.5.0_04, with JAI 1.1.2_01 and Image IO 1.1. In some circumstances (we never figured out exactly why), when we were processing large images (but not that large - a few MB), the JVM would crash without any error message or stack trace or anything. This didn't happen much in production, but enough to be a nuisance and eventually we were able to reproduce it. We decided to switch to JRockit90 1.5.0_04 and we were no longer able to reproduce the problem in our test environment, so we thought we had it licked. Now, however, after the application server has been up for a while, we start getting the error message, "Not enough storage is available to process this command" during image operations. For example: java.lang.Error: Error starting thread: Not enough storage is available to process this command. at java.lang.Thread.start()V(Unknown Source) at sun.awt.image.ImageFetcher$1.run(ImageFetcher.java:279) at sun.awt.image.ImageFetcher.createFetchers(ImageFetcher.java:272) at sun.awt.image.ImageFetcher.add(ImageFetcher.java:55) at sun.awt.image.InputStreamImageSource.startProduction(InputStreamImageSource.java:149) at sun.awt.image.InputStreamImageSource.addConsumer(InputStreamImageSource.java:106) at sun.awt.image.InputStreamImageSource.startProduction(InputStreamImageSource.java:144) at sun.awt.image.ImageRepresentation.startProduction(ImageRepresentation.java:647) at sun.awt.image.ImageRepresentation.prepare(ImageRepresentation.java:684) at sun.awt.SunToolkit.prepareImage(SunToolkit.java:734) at java.awt.Component.prepareImage(Component.java:3073) at java.awt.ImageMediaEntry.startLoad(MediaTracker.java:906) at java.awt.MediaEntry.getStatus(MediaTracker.java:851) at java.awt.ImageMediaEntry.getStatus(MediaTracker.java:902) at java.awt.MediaTracker.statusAll(MediaTracker.java:454) at java.awt.MediaTracker.waitForAll(MediaTracker.java:405) at java.awt.MediaTracker.waitForAll(MediaTracker.java:375) at SfxNET.System.Drawing.ImageLoader.loadImage(Ljava.awt.Image;)Ljava.awt.image.BufferedImage;(Unknown Source) at SfxNET.System.Drawing.ImageLoader.loadImage(Ljava.net.URL;)Ljava.awt.image.BufferedImage;(Unknown Source) at Resources.Tools.Commands.W$zw(Ljava.lang.ClassLoader;)V(Unknown Source) at Resources.Tools.Commands.getContents()[[Ljava.lang.Object;(Unknown Source) at SfxNET.sfxUtils.SfxResourceBundle.handleGetObject(Ljava.lang.String;)Ljava.lang.Object;(Unknown Source) at java.util.ResourceBundle.getObject(ResourceBundle.java:320) at SoftwareFX.internal.ChartFX.wxvw.yxWW(Ljava.lang.String;Z)Ljava.lang.Object;(Unknown Source) at SoftwareFX.internal.ChartFX.wxvw.vxWW(Ljava.lang.String;)Ljava.lang.Object;(Unknown Source) at SoftwareFX.internal.ChartFX.CommandBar.YWww(LSoftwareFX.internal.ChartFX.wxvw;IIII)V(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.xxvw.YzzW(LSoftwareFX.internal.ChartFX.Internet.Server.ChartCore;Z)LSoftwareFX.internal.ChartFX.CommandBar;(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.xxvw.XzzW(LSoftwareFX.internal.ChartFX.Internet.Server.ChartCore;)V(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.ChartCore.OnDeserialization(Ljava.lang.Object;)V(Unknown Source) at SoftwareFX.internal.ChartFX.Internet.Server.ChartCore.Zvvz(LSoftwareFX.internal.ChartFX.Base.wzzy;)V(Unknown Source) Has anyone seen something like this before? Any clue what might be happening?

    Read the article

  • How to fix the position of the button in applet

    - by user1609804
    I'm trying to make an applet that has a buttons in the right, where each button is corresponding to a certain pokemon. I already did it, but the buttons isn't fixed.they keep following the mouse. please help. This is my code: import javax.swing.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import java.applet.*; import java.awt.event.*; import java.awt.*; public class choosePokemon extends Applet implements ActionListener { private int countPokemon; private int[] storePokemon; private int x,y; //this will be the x and y coordinate of the button BufferedImage Picture; public int getCountPokemon(){ //for other class that needs how many pokemon return countPokemon; } public int[] getStoredPokemon(){ //for other class that needs the pokemon return storePokemon; } public void init(){ x=0;y=0; try{ Picture = ImageIO.read(new File("pokeball.png")); } catch( IOException ex ){ } } public void paint( Graphics g ){ pokemon display = new pokemon(); // to access the pokemon attributes in class pokemon ButtonGroup group = new ButtonGroup(); //create a button group for( int a=0;a<16;a++ ){ // for loop in displaying the buttons of every pokemon(one pokemon, one button) display.choose( a ); //calls the method choose in which accepts an integer from 0-15 and saves the attributes of the pokemon corresponding to the integer JButton pokemonButton = new JButton( display.getName() ); // creates the button pokemonButton.setActionCommand( display.getName() ); // isasave sa actioncommand yung name ng kung ano mang pokemon pokemonButton.addActionListener(this); //isasama yung bagong gawang button sa listener para malaman kung na-click yung button pokemonButton.setBounds( x,y,50,23 ); group.add( pokemonButton ); //eto naman yung mag-aadd sa bagong gawang button sa isang group na puro buttons(button ng mga pokemon) y+=23; if( a==7 ){ x+=50; y=0; } add( pokemonButton ); //will add the button to the applet } g.drawImage( Picture, 120, 20, null ); } public void actionPerformed(ActionEvent e) { try{ //displays the picture of the selected pokemon Picture = ImageIO.read(new File( "pokemon/" + e.getActionCommand() + ".png" )); } catch( IOException ex ){ } } public boolean chosen( int PChoice ){ //this will check if the chosen pokemon is already the player's pokemon boolean flag = false; for( int x=0; x<countPokemon && !flag ;x++ ){ if( storePokemon[x]==PChoice ){ flag = true; } } return flag; }

    Read the article

  • Working with images in Scala

    - by dbyrne
    I am generating large PNG files from a Scala program. Currently, I am doing it the same way I would do it in java. I am creating a new BufferedImage and setting each pixel to the correct color. This works fine, but I am wondering if there are any good libraries for working with images in Scala? I am looking for something like Ruby's RMagick library.

    Read the article

  • How to use sound and images in a Java applet?

    - by Click Upvote
    Question 1: How should I structure my project so the sound and images files can be loaded most easily? Right now, I have the folder: C:\java\pacman with the sub-directory C:\java\pacman\src containing all the code, and C:\java\pacman\assets containing the images and .wav files. Is this the best structure or should I put the assets somewhere else? Question 2: What's the best way to refer to the images/sounds without using the full path e.g C:\java\pacman\assets\something.png to them? If I use the getCodeBase() function it seems to refer to the C:\java\pacman\bin instead of C:\java\pacman\. I want to use such a function/class which would work automatically when i compile the applet in a jar as well as right now when I test the applet through eclipse. Question 3: How should I load the images/sounds? This is what I'm using now: 1) For general images: import java.awt.Image; public Image getImg(String file) { //imgDir in this case is a hardcoded string containing //"C:\\java\\pacman\\assets\\" file=imgDir + file; return new ImageIcon(file).getImage(); } The images returned from this function are used in the drawImage method of the Graphics class in the paint method of the applet. 2) For a buffered image, which is used to get subImages and load sprites from a sprite sheet: public BufferedImage getSheet() throws IOException { return ImageIO.read(new File(img.getPath("pacman-sprites.png"))); } Later: public void loadSprites() { BufferedImage sheet; try { sheet=getSheet(); redGhost.setNormalImg(sheet.getSubimage(0, 60, 20, 20)); redGhost.setUpImg(sheet.getSubimage(0, 60, 20, 20)); redGhost.setDownImg(sheet.getSubimage(30, 60, 20, 20)); redGhost.setLeftImg(sheet.getSubimage(30, 60, 20, 20)); redGhost.setRightImg(sheet.getSubimage(60, 60, 20, 20)); } catch (IOException e) { System.out.println("Couldnt open file!"); System.out.println(e.getLocalizedMessage()); } } 3) For sound files: import sun.audio.*; import java.io.*; public synchronized void play() { try { InputStream in = new FileInputStream(filename); AudioStream as = new AudioStream(in); AudioPlayer.player.start(as); } catch (IOException e) { e.printStackTrace(); } }

    Read the article

  • Problem with my whiteboard application

    - by swift
    I have to develop a whiteboard application in which both the local user and the remote user should be able to draw simultaneously, is this possible? If possible then any logic? I have already developed a code but in which i am not able to do this, when the remote user starts drawing the shape which i am drawing is being replaced by his shape and co-ordinates. This problem is only when both draw simultaneously. any idea guys? Here is my code class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; int bpressed; Color color; Point start; Point end; Point mp; Button elipse=new Button("elipse"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button empty=new Button(""); JButton save=new JButton("Save"); JButton erase=new JButton("Erase"); String selected; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Point p=new Point(); int w,h; public Paper(DatagramSocket dataSocket) { this.dataSocket=dataSocket; client=new Client(dataSocket); System.out.println("paper"); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); //save.setPreferredSize(new Dimension(100,20)); save.setMaximumSize(new Dimension(75,27)); erase.setMaximumSize(new Dimension(75,27)); } public void paintComponent(Graphics g) { try { g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); repaint(); g2.dispose(); start=null; } //To add the point to the board which is broadcasted by the server public synchronized void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) selected="elipse"; else if(shape.equals("line")) selected="line"; else if(shape.equals("rect")) selected="rect"; else if(shape.equals("erase")) { selected="erase"; erase(); } if(end!=null && start!=null) { if(varname.equals("end")) end=ps; if(varname.equals("mp")) mp=ps; if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } } catch(Exception e) { e.printStackTrace(); } } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); pic.fillRect(start.x, start.y, 10, 10); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); JPanel row1=new JPanel(); JPanel row2=new JPanel(); JPanel row3=new JPanel(); JPanel row4=new JPanel(); buttonpanel.setPreferredSize(new Dimension(80,80)); //buttonpanel.setMinimumSize(new Dimension(150,150)); row1.setLayout(new BoxLayout(row1,BoxLayout.X_AXIS)); row1.setPreferredSize(new Dimension(150,150)); row2.setLayout(new BoxLayout(row2,BoxLayout.X_AXIS)); row3.setLayout(new BoxLayout(row3,BoxLayout.X_AXIS)); row4.setLayout(new BoxLayout(row4,BoxLayout.X_AXIS)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener( this); save.addActionListener( this); erase.addActionListener( this); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row1.add(elipse); row1.add(Box.createRigidArea(new Dimension(5,0))); row1.add(rectangle); buttonpanel.add(row1); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row2.add(line); row2.add(Box.createRigidArea(new Dimension(5,0))); row2.add(empty); buttonpanel.add(row2); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row3.add(save); buttonpanel.add(row3); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row4.add(erase); buttonpanel.add(row4); return buttonpanel; } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase") { start=e.getPoint(); client.broadcast(start,"start", selected,"press"); } else if(selected=="elipse"||selected=="rect") { mp = e.getPoint(); client.broadcast(mp,"mp", selected,"press"); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release"); } else if(selected=="elipse"||selected=="rect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release"); } draw(); } //start=null; } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag"); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag"); } else if(selected=="elipse"||selected=="rect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag"); client.broadcast(end,"end", selected,"drag"); } repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; if(e.getSource()==rectangle) selected="rect"; if(e.getSource()==save) save(); if(e.getSource()==erase) { selected="erase"; erase(); } } } class Button extends JButton { String name; public Button(String name) { this.name=name; Dimension buttonSize = new Dimension(35,35); setMaximumSize(buttonSize); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); } }

    Read the article

  • Modifying and Manipulating a interactive bezier curve

    - by rachel
    This is a homework question and I'm having a lot of trouble with it - I've managed to do some of it but still cant finish it - can i Please get some help. Q1. Bezier Curves The following example allows you to interactively control a bezier curve by dragging the control points Cubic.java Replace the call to draw the cubic shape (big.draw(cubic)), by your own function to draw a bezier by the recursive split method. Finally, add the ability to create a longer Bezier curve by adding more control points to create a second curve. Cubic.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.applet.Applet; import java.awt.geom.*; import java.awt.image.BufferedImage; public class Cubic extends JApplet{ static protected JLabel label; CubicPanel cubicPanel; public void init(){ //Initialize the layout. getContentPane().setLayout(new BorderLayout()); cubicPanel = new CubicPanel(); cubicPanel.setBackground(Color.white); getContentPane().add(cubicPanel); label = new JLabel("Drag the points to adjust the curve."); getContentPane().add("South", label); } public static void main(String s[]) { JFrame f = new JFrame("Cubic"); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); JApplet applet = new Cubic(); f.getContentPane().add(applet, BorderLayout.CENTER); applet.init(); f.setSize(new Dimension(350,250)); f.setVisible(true); } } class CubicPanel extends JPanel implements MouseListener, MouseMotionListener{ BufferedImage bi; Graphics2D big; int x, y; Rectangle area, startpt, endpt, onept, twopt, rect; CubicCurve2D.Double cubic = new CubicCurve2D.Double(); Point2D.Double start, end, one, two, point; boolean firstTime = true; boolean pressOut = false; public CubicPanel(){ setBackground(Color.white); addMouseMotionListener(this); addMouseListener(this); start = new Point2D.Double(); one = new Point2D.Double(); two = new Point2D.Double(); end = new Point2D.Double(); cubic.setCurve(start, one, two, end); startpt = new Rectangle(0, 0, 8, 8); endpt = new Rectangle(0, 0, 8, 8); onept = new Rectangle(0, 0, 8, 8); twopt = new Rectangle(0, 0, 8, 8); } public void mousePressed(MouseEvent e){ x = e.getX(); y = e.getY(); if(startpt.contains(x, y)){ rect = startpt; point = start; x = startpt.x - e.getX(); y = startpt.y - e.getY(); updateLocation(e); } else if(endpt.contains(x, y)){ rect = endpt; point = end; x = endpt.x - e.getX(); y = endpt.y - e.getY(); updateLocation(e); } else if(onept.contains(x, y)){ rect = onept; point = one; x = onept.x - e.getX(); y = onept.y - e.getY(); updateLocation(e); } else if(twopt.contains(x, y)){ rect = twopt; point = two; x = twopt.x - e.getX(); y = twopt.y - e.getY(); updateLocation(e); } else { pressOut = true; } } public void mouseDragged(MouseEvent e){ if(!pressOut) { updateLocation(e); } } public void mouseReleased(MouseEvent e){ if(startpt.contains(e.getX(), e.getY())){ rect = startpt; point = start; updateLocation(e); } else if(endpt.contains(e.getX(), e.getY())){ rect = endpt; point = end; updateLocation(e); } else if(onept.contains(e.getX(), e.getY())){ rect = onept; point = one; updateLocation(e); } else if(twopt.contains(e.getX(), e.getY())){ rect = twopt; point = two; updateLocation(e); } else { pressOut = false; } } public void mouseMoved(MouseEvent e){} public void mouseClicked(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void updateLocation(MouseEvent e){ rect.setLocation((x + e.getX())-4, (y + e.getY())-4); point.setLocation(x + e.getX(), y + e.getY()); checkPoint(); cubic.setCurve(start, one, two, end); repaint(); } public void paintComponent(Graphics g){ super.paintComponent(g); update(g); } public void update(Graphics g){ Graphics2D g2 = (Graphics2D)g; Dimension dim = getSize(); int w = dim.width; int h = dim.height; if(firstTime){ // Create the offsecren graphics to render to bi = (BufferedImage)createImage(w, h); big = bi.createGraphics(); // Get some initial positions for the control points start.setLocation(w/2-50, h/2); end.setLocation(w/2+50, h/2); one.setLocation((int)(start.x)+25, (int)(start.y)-25); two.setLocation((int)(end.x)-25, (int)(end.y)+25); // Set the initial positions of the squares that are // drawn at the control points startpt.setLocation((int)((start.x)-4), (int)((start.y)-4)); endpt.setLocation((int)((end.x)-4), (int)((end.y)-4)); onept.setLocation((int)((one.x)-4), (int)((one.y)-4)); twopt.setLocation((int)((two.x)-4), (int)((two.y)-4)); // Initialise the CubicCurve2D cubic.setCurve(start, one, two, end); // Set some defaults for Java2D big.setColor(Color.black); big.setStroke(new BasicStroke(5.0f)); big.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); area = new Rectangle(dim); firstTime = false; } // Clears the rectangle that was previously drawn. big.setColor(Color.white); big.clearRect(0, 0, area.width, area.height); // Set the colour for the bezier big.setPaint(Color.black); // Replace the following line by your own function to // draw the bezier specified by start, one, two, end big.draw(cubic); // Draw the control points big.setPaint(Color.red); big.fill(startpt); big.setPaint(Color.magenta); big.fill(endpt); big.setPaint(Color.blue); big.fill(onept); big.setPaint(new Color(0, 200, 0)); big.fill(twopt); // Draws the buffered image to the screen. g2.drawImage(bi, 0, 0, this); } /* Checks if the rectangle is contained within the applet * window. If the rectangle is not contained withing the * applet window, it is redrawn so that it is adjacent to the * edge of the window and just inside the window. */ void checkPoint(){ if (area == null) { return; } if((area.contains(rect)) && (area.contains(point))){ return; } int new_x = rect.x; int new_y = rect.y; double new_px = point.x; double new_py = point.y; if((rect.x+rect.width)>area.getWidth()){ new_x = (int)area.getWidth()-(rect.width-1); } if(point.x > area.getWidth()){ new_px = (int)area.getWidth()-1; } if(rect.x < 0){ new_x = -1; } if(point.x < 0){ new_px = -1; } if((rect.y+rect.width)>area.getHeight()){ new_y = (int)area.getHeight()-(rect.height-1); } if(point.y > area.getHeight()){ new_py = (int)area.getHeight()-1; } if(rect.y < 0){ new_y = -1; } if(point.y < 0){ new_py = -1; } rect.setLocation(new_x, new_y); point.setLocation(new_px, new_py); } }

    Read the article

  • get eigenvalue pca with java

    - by Muhamad Burhanudin
    I try use PCA to reduce dimention, and i use jama for help me using matrix. but, i got problem when get eigenvalue with jama. for example i hava 2 image dimention 100x100, then i create single matrix 2 image x (100x100). there is 20.000 pixel. and how to get reduction with eigenvalue? this is sample my code : public static void main(String[] args) { BufferedImage bi; int[] rgb; int R, G, B; // int[] jum; double[][] gray = new double[500][500] ; String[] baris = new String[1000]; try { //bi = ImageIO.read(new File("D:\\c.jpg")); int[][] pixelData = new int[bi.getHeight() * bi.getWidth()][3]; int counter = 0; for (int i = 0; i < bi.getHeight(); i++) { for (int j = 0; j < bi.getWidth(); j++) { gray[i][j] = getPixelData(bi, i, j); // R = getR(bi, i, j); //G = getG(bi, i, j); //B = getB(bi, i, j); //jum = R + G + B; // gray[counter] = Double.toString(R + G + B / 3); // System.out.println("Gray " +gray); //for (int k = 0; k < rgb.length; k++) { // pixelData[counter][k] = rgb[k]; // } counter++; } } } catch (IOException e) { e.printStackTrace(); } Matrix matrix = new Matrix(gray); PCA pca = new PCA(matrix); pca.getEigenvalue(6); String n = pca.toString(); System.err.println("nilai n "+n); //double dete = pcadete(matrix,3600); } private static int getPixelData(BufferedImage bi, int x, int y) { int argb = bi.getRGB(y, x); int r, g, b; int gray; int rgb[] = new int[]{ (argb >> 16) & 0xff, //red (argb >> 8) & 0xff, //green (argb) & 0xff //blue }; r = rgb[0]; g = rgb[1]; b = rgb[2]; gray = (r + g + b) / 3; System.out.println("gray: " + gray); return gray; } when i show eigenvalue in this code : PCA pca = new PCA(matrix); pca.getEigenvalue(6); String n = pca.toString(); System.err.println("nilai n "+n); Result is : nilai n PCA@c3e9e9 Can, u tell me what way to get eigenvalue and reduction dimension.

    Read the article

  • output image is not displayed

    - by gerry chocolatos
    so, im doing an image detection which i have to process on each red, green, n blue element to get the edge map and combine them become one to show the output. but it doesnt show my output image would anyone pls be kind enough to help me? here is my code so far. //get the red element process_red = new int[width * height]; counter = 0; for(int i = 0; i < 256; i++) { for(int j = 0; j < 256; j++) { int clr = buff_red.getRGB(j, i); int red = (clr & 0x00ff0000) >> 16; red = (0xFF<<24)|(red<<16)|(red<<8)|red; process_red[counter] = red; counter++; } } //set threshold value for red element int threshold = 100; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int bin = (buff_red.getRGB(x, y) & 0x000000ff); if (bin < threshold) bin = 0; else bin = 255; buff_red.setRGB(x,y, 0xff000000 | bin << 16 | bin << 8 | bin); } } and i do the same way for my green n blue elements. and then i wanted to get to combination of the three by doing it this way: //combine the three elements process_combine = new int[width * height]; counter = 0; for(int i = 0; i < 256; i++) { for(int j = 0; j < 256; j++) { int clr_a = buff_red.getRGB(j, i); int ar = clr_a & 0x000000ff; int clr_b = buff_green.getRGB(j, i); int bg = clr_b & 0x000000ff; int clr_c = buff_blue.getRGB(j, i); int cb = clr_b & 0x000000ff; int alpha = 0xff000000; int combine = alpha|(ar<<16)|(bg<<8)|cb; process_combine[counter] = combine; counter++; } } buff_rgb = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB); Graphics rgb; rgb = buff_rgb.getGraphics(); rgb.drawImage(output_rgb, 0, 0, null); rgb.dispose(); repaint(); and to show the output whic is from the combining process, i use a draw method: g.drawImage(buff_rgb,800,100,this); but still it doesnt show the image. can anyone pls help me? ur help is really appreciated. thanks.

    Read the article

  • How to customize the renders in prefuse. Problem in customize images in prefuse layout

    - by user324926
    HI all, I have written a java application to show the images in different layouts. I am able to show it different layout correctly but some times the images are overlapped. Can you please help me, how to solve this problem. My code is given below `import javax.swing.JFrame; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.util.; import java.io.; import java.awt.Font; import prefuse.Constants; import prefuse.Display; import prefuse.Visualization; import prefuse.action.ActionList; import prefuse.action.RepaintAction; import prefuse.action.assignment.ColorAction; import prefuse.action.assignment.FontAction; import prefuse.action.assignment.DataColorAction; import prefuse.action.layout.graph.ForceDirectedLayout; import prefuse.action.layout.graph.; import prefuse.action.layout.; import prefuse.activity.Activity; import prefuse.controls.DragControl; import prefuse.controls.PanControl; import prefuse.controls.ZoomControl; import prefuse.data.Graph; import prefuse.data.io.DataIOException; import prefuse.data.io.GraphMLReader; import prefuse.render.DefaultRendererFactory; import prefuse.render.LabelRenderer; import prefuse.util.ColorLib; import prefuse.visual.VisualItem; import prefuse.visual.*; import prefuse.util.FontLib; import prefuse.action.assignment.DataSizeAction; import prefuse.data.*; import prefuse.render.ImageFactory; public class LayoutExample { public static void main(String[] argv) throws Exception { Graph graph = null; try { graph = new GraphMLReader().readGraph("/graphs.xml"); } catch ( DataIOException e ) { e.printStackTrace(); System.err.println("Error loading graph. Exiting..."); System.exit(1); } ImageFactory imageFactory = new ImageFactory(100,100); try { //load images and construct imageFactory. String images[] = new String[3]; images[0] = "data/images/switch.png"; images[1] = "data/images/ip_network.png"; images[2] = "data/images/router.png"; String[] names = new String[] {"Switch","Network","Router"}; BufferedImage img = null; for(int i=0; i < images.length ; i++) { try { img = ImageIO.read(new File(images[i])); imageFactory.addImage(names[i],img); } catch (IOException e){ } } } catch(Exception exp) { } Visualization vis = new Visualization(); vis.add("graph", graph); LabelRenderer nodeRenderer = new LabelRenderer("name", "type"); nodeRenderer.setVerticalAlignment(Constants.BOTTOM); nodeRenderer.setHorizontalPadding(0); nodeRenderer.setVerticalPadding(0); nodeRenderer.setImagePosition(Constants.TOP); nodeRenderer.setMaxImageDimensions(100,100); DefaultRendererFactory drf = new DefaultRendererFactory(); drf.setDefaultRenderer(nodeRenderer); vis.setRendererFactory(drf); ColorAction nText = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR); nText.setDefaultColor(ColorLib.gray(100)); ColorAction nEdges = new ColorAction("graph.edges", VisualItem.STROKECOLOR); nEdges.setDefaultColor(ColorLib.gray(100)); // bundle the color actions ActionList draw = new ActionList(); //MAD - changing the size of the nodes dependent on the weight of the people final DataSizeAction dsa = new DataSizeAction("graph.nodes","size"); draw.add(dsa); draw.add(nText); draw.add(new FontAction("graph.nodes", FontLib.getFont("Tahoma",Font.BOLD, 12))); draw.add(nEdges); vis.putAction("draw", draw); ActionList layout = new ActionList(Activity.DEFAULT_STEP_TIME); BalloonTreeLayout balloonlayout = new BalloonTreeLayout("graph",50); layout.add(balloonlayout); Display d = new Display(vis); vis.putAction("layout", layout); // start up the animated layout vis.run("draw"); vis.run("layout"); d.addControlListener(new DragControl()); // pan with left-click drag on background d.addControlListener(new PanControl()); // zoom with right-click drag d.addControlListener(new ZoomControl()); // -- 6. launch the visualization ------------------------------------- // create a new window to hold the visualization JFrame frame = new JFrame("prefuse example"); // ensure application exits when window is closed frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(d); frame.pack(); // layout components in window frame.setVisible(true); // show the window } } ` Can anyone please let me know how to customize the image sizes / renders insuch way that images won't overlapped. Thanks R.Ravikumar

    Read the article

  • JNI unsigned char to byte array

    - by Jeff Storey
    I'm working with a C++ library that stores image byte data in an array of unsigned characters. My jni function returns a jByteArray (which then gets converted to a BufferedImage on the java side), but I'm not sure how to fill the jByteArray from the unsigned character array (if it is possible). Can anyone provide a snippet for this last part to basically do this: // size is the size of the unsigned char array const int size = 100; unsigned char* buf = new unsigned char[size]; // buf gets passed to another library here to be populated jbyteArray bArray = env->NewByteArray(size); // now how do I get the data from buf to bArray? Thanks, Jeff

    Read the article

  • How to make video in Java captured from webcam through lti-Civil CaptureDeviceStream ?

    - by i.Psi
    Can I do it only with the lti-Civil classes or I need FMJ or JMF ? do I use the actual Stream or set of captured Images from CaptureObserver? Thanks. captureStream = system.openCaptureDeviceStream(info.getDeviceID()); captureStream.setObserver(new CaptureObserver(){ public void onError(CaptureStream arg0, CaptureException arg1) { } public void onNewImage(CaptureStream streamSource, Image image) { try { imageFrame.setImage(AWTImageConverter.toBufferedImage(image)); bufferedImage = AWTImageConverter.toBufferedImage(image); } catch (Throwable t) { t.printStackTrace(); } } }); captureStream.start();

    Read the article

  • Which containers / graphics components to use in a simple Java Swing game?

    - by rize
    I'm creating a simple labyrinth game with Java + Swing. The game draws a randomized labyrinth on the screen, places a figure in the middle, and the player is then supposed to find the way out by moving the figure with arrow-keys. As for now, I'm using a plain background and drawing the walls of the labyrinth with Graphics.drawLine(). I have a custom picture of the figure in a .gif file, which I load as a BufferedImage object. However, I want the player to see only part of the labyrinth at a time, and the screen should follow the figure in the game, as the player moves around. I'm planning to do this by creating an Image object of the whole labyrinth when it is created, and then "cutting" a square around the current position of the figure and displaying this with Graphics.drawImage(). I'm new with Swing though, and I can't figure out how to draw the figure at different positions "above" the labyrinth without redrawing the whole thing. Which container/component should I use for the labyrinth and then for the figure to achieve this?

    Read the article

  • Java: Line appears when using AffineTransform to scale image

    - by Malakim
    Hi, I'm having a problem with image scaling. When I use the following code to scale an image it ends up with a line either at the bottom or on the right side of the image. double scale = 1; if (scaleHeight >= scaleWidth) { scale = scaleWidth; } else { scale = scaleHeight; } AffineTransform af = new AffineTransform(); af.scale(scale, scale); AffineTransformOp operation = new AffineTransformOp(af, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); BufferedImage bufferedThumb = operation.filter(img, null); The original image is here: http://tinyurl.com/yzv6r7h The scaled image: http://tinyurl.com/yk6e8ga Does anyone know why the line appears? Thanks!

    Read the article

  • How to save optimized png images with java's ImageIO?

    - by Christoph
    I am generating lots of images in java and saving them through the ImageIO.write method like this: final BufferedImage img = createSomeImage(); ImageIO.write( img, "png", new File( "/some/file.png" ); I was happy with the results until Google's firefox addon 'Page Speed' told me that i can save up to 60% of the size if i optimize the images. The images are QR codes, their size is around 900B each and the firefox-plugin optimized versions are around 300B. I'd like to save such optimized 300B Images directly from java. So here my question again: How to save optimized png images with java's ImageIO?

    Read the article

< Previous Page | 1 2 3 4 5 6  | Next Page >