Search Results

Search found 258 results on 11 pages for 'drawimage'.

Page 3/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Animation Trouble with Java Swing Timer - Also, JFrame Will Not Exit_On_Close

    - by forgotton_semicolon
    So, I am using a Java Swing Timer because putting the animation code in a run() method of a Thread subclass caused an insane amount of flickering that is really a terrible experience for any video game player. Can anyone give me any tips on: Why there is no animation... Why the JFrame will not close when it is coded to Exit_On_Close 2 times My code is here: import java.awt.; import java.awt.event.; import javax.swing.*; import java.net.URL; //////////////////////////////////////////////////////////////// TFQ public class TFQ extends JFrame { DrawingsInSpace dis; //========================================================== constructor public TFQ() { dis = new DrawingsInSpace(); JPanel content = new JPanel(); content.setLayout(new FlowLayout()); this.setContentPane(dis); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setTitle("Plasma_Orbs_Off_Orion"); this.setSize(500,500); this.pack(); //... Create timer which calls action listener every second.. // Use full package qualification for javax.swing.Timer // to avoid potential conflicts with java.util.Timer. javax.swing.Timer t = new javax.swing.Timer(500, new TimePhaseListener()); t.start(); } /////////////////////////////////////////////// inner class Listener thing class TimePhaseListener implements ActionListener, KeyListener { // counter int total; // loop control boolean Its_a_go = true; //position of our matrix int tf = -400; //sprite directions int Sprite_Direction; final int RIGHT = 1; final int LEFT = 2; //for obstacle Rectangle mega_obstacle = new Rectangle(200, 0, 20, HEIGHT); public void actionPerformed(ActionEvent e) { //... Whenever this is called, repaint the screen dis.repaint(); addKeyListener(this); while (Its_a_go) { try { dis.repaint(); if(Sprite_Direction == RIGHT) { dis.matrix.x += 2; } // end if i think if(Sprite_Direction == LEFT) { dis.matrix.x -= 2; } } catch(Exception ex) { System.out.println(ex); } } // end while i think } // end actionPerformed @Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent event) { // TODO Auto-generated method stub if (event.getKeyChar()=='f'){ Sprite_Direction = RIGHT; System.out.println("matrix should be animating now "); System.out.println("current matrix position = " + dis.matrix.x); } if (event.getKeyChar()=='d') { Sprite_Direction = LEFT; System.out.println("matrix should be going in reverse"); System.out.println("current matrix position = " + dis.matrix.x); } } } //================================================================= main public static void main(String[] args) { JFrame SafetyPins = new TFQ(); SafetyPins.setVisible(true); SafetyPins.setSize(500,500); SafetyPins.setResizable(true); SafetyPins.setLocationRelativeTo(null); SafetyPins.setDefaultCloseOperation(EXIT_ON_CLOSE); } } class DrawingsInSpace extends JPanel { URL url1_plasma_orbs; URL url2_matrix; Image img1_plasma_orbs; Image img2_matrix; // for the plasma_orbs Rectangle bbb = new Rectangle(0,0, 0, 0); // for the matrix Rectangle matrix = new Rectangle(-400, 60, 430, 200); public DrawingsInSpace() { //load URLs try { url1_plasma_orbs = this.getClass().getResource("plasma_orbs.png"); url2_matrix = this.getClass().getResource("matrix.png"); } catch(Exception e) { System.out.println(e); } // attach the URLs to the images img1_plasma_orbs = Toolkit.getDefaultToolkit().getImage(url1_plasma_orbs); img2_matrix = Toolkit.getDefaultToolkit().getImage(url2_matrix); } public void paintComponent(Graphics g) { super.paintComponent(g); // draw the plasma_orbs g.drawImage(img1_plasma_orbs, bbb.x, bbb.y,this); //draw the matrix g.drawImage(img2_matrix, matrix.x, matrix.y, this); } } // end class enter code here

    Read the article

  • Using UIScreen to drive a VGA display - doesn't seem to show the UIWindow?

    - by Peter Hajas
    HI there, I'm trying to use UIScreen to drive a separate screen with the VGA dongle on my iPad. Here's what I've got in my root view controller's viewDidLoad: //Code to detect if an external display is connected to the iPad. NSLog(@"Number of screens: %d", [[UIScreen screens]count]); //Now, if there's an external screen, we need to find its modes, itereate through them and find the highest one. Once we have that mode, break out, and set the UIWindow. if([[UIScreen screens]count] > 1) //if there are more than 1 screens connected to the device { CGSize max; UIScreenMode *maxScreenMode; for(int i = 0; i < [[[[UIScreen screens] objectAtIndex:1] availableModes]count]; i++) { UIScreenMode *current = [[[[UIScreen screens]objectAtIndex:1]availableModes]objectAtIndex:i]; if(current.size.width > max.width); { max = current.size; maxScreenMode = current; } } //Now we have the highest mode. Turn the external display to use that mode. UIScreen *external = [[UIScreen screens] objectAtIndex:1]; external.currentMode = maxScreenMode; //Boom! Now the external display is set to the proper mode. We need to now set the screen of a new UIWindow to the external screen external_disp = [externalDisplay alloc]; external_disp.drawImage = drawViewController.drawImage; UIWindow *newwindow = [UIWindow alloc]; [newwindow addSubview:external_disp.view]; newwindow.screen = external; }

    Read the article

  • Right way to dispose Image/Bitmap and PictureBox

    - by kornelijepetak
    I am trying to develop a Windows Mobile 6 (in WF/C#) application. There is only one form and on the form there is only a PictureBox object. On it I draw all desired controls or whatever I want. There are two things I am doing. Drawing custom shapes and loading bitmaps from .png files. The next line locks the file when loading (which is an undesired scenario): Bitmap bmp = new Bitmap("file.png"); So I am using another way to load bitmap. public static Bitmap LoadBitmap(string path) { using (Bitmap original = new Bitmap(path)) { return new Bitmap(original); } } This is I guess much slower, but I don't know any better way to load an image, while quickly releasing the file lock. Now, when drawing an image there is method that I use: public void Draw() { Bitmap bmp = new Bitmap(240,320); Graphics g = Graphics.FromImage(bmp); // draw something with Graphics here. g.Clear(Color.Black); g.DrawImage(Images.CloseIcon, 16, 48); g.DrawImage(Images.RefreshIcon, 46, 48); g.FillRectangle(new SolidBrush(Color.Black), 0, 100, 240, 103); pictureBox.Image = bmp; } This however seems to be some kind of a memory leak. And if I keep doing it for too long, the application eventually crashes. Therefor, I have X questions: 1.) What is the better way for loading bitmaps from files without locking the file? 2.) What objects needs to be manually disposed in the Draw() function (and in which order) so there's no memory leak and no ObjectDisposedException throwing? 3.) If pictureBox.Image is set to bmp, like in the last line of the code, would pictureBox.Image.Dispose() dispose only resources related to maintaining the pictureBox.Image or the underlying Bitmap set to it?

    Read the article

  • trying to draw scaled UIImage in custom view, but nothing's rendering

    - by Ben Collins
    I've created a custom view class and right now just want to draw an image scaled to fit the view, given a UIImage. I tried just drawing the UIImage.CGImage, but as others have attested to on this site (and in the docs), that renders the image upside down. So, at the suggestion of an answer I found to another question, I'm trying to draw it directly, but nothing is rendering in the view and I'm not sure why. Here's my drawing code: - (void)drawRect:(CGRect)rect { // Drawing code [super drawRect:rect]; if (self.originalImage) { [self drawImage]; } } - (void) drawImage { if (CGSizeEqualToSize(originalImage.size, self.frame.size) == NO) { CGFloat scaleFactor = 1.0; CGFloat scaledWidth = 0.0; CGFloat scaledHeight = 0.0; CGPoint thumbPoint = CGPointMake(0.0, 0.0); CGFloat widthFactor = self.frame.size.width / originalImage.size.width; CGFloat heightFactor = self.frame.size.height / originalImage.size.height; if (widthFactor < heightFactor) { scaleFactor = widthFactor; } else { scaleFactor = heightFactor; } scaledWidth = originalImage.size.width * scaleFactor; scaledHeight = originalImage.size.height * scaleFactor; if (widthFactor < heightFactor) { thumbPoint.y = (self.frame.size.height - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbPoint.x = (self.frame.size.width - scaledWidth) * 0.5; } UIGraphicsBeginImageContext(self.frame.size); CGRect thumbRect = CGRectZero; thumbRect.origin = thumbPoint; thumbRect.size.width = scaledWidth; thumbRect.size.height = scaledHeight; [originalImage drawInRect:thumbRect]; self.scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } else { self.scaledImage = originalImage; } } My understanding (after studying this a bit) is that the UIGraphicsBeginImageContext function creates an offscreen for me to draw into, so now how do I render that context on top of the original one?

    Read the article

  • Problem draw line by Quartz 2D with alpha property < 1.0 on iPhone

    - by The Khanh
    Hello Everybody ! This code i use to draw in my app. So i have problem, if i draw with alpha property = 1. It is very good but if i change alpha property = 0.2 then my paint is not good. How do i make for better with alpha property = 0.2. http://www.flickr.com/photos/9601621@N05/page1/ Draw with alpha = 1: It is good Draw with alpha = 0.2: It is bad - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { if ([self.view superview] && (headerView.frame.origin.y == -30)) { mouseSwiped = YES; UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self.view]; currentPoint.y -= 20; UIGraphicsBeginImageContext(self.view.frame.size); CGContextRef context = UIGraphicsGetCurrentContext(); [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; CGContextSetLineCap(context, kCGLineCapRound); CGContextSetLineWidth(context, currentBrushProperty.brushSize); CGContextSetRGBStrokeColor(context, [self red], [self green], [self blue], currentBrushProperty.brushTransparency); CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); CGContextBeginPath(context); CGContextMoveToPoint(context, lastPoint.x, lastPoint.y); CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y); CGContextStrokePath(context); drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); lastPoint = currentPoint; }} Help me, please.

    Read the article

  • Can you have multiple clipping regions in an HTML Canvas?

    - by emh
    I have code that loads a bunch of images into hidden img elements and then a Javascript loop which places each image onto the canvas. However, I want to clip each image so that it is a circle when placed on the canvas. My loop looks like this: $$('#avatars img').each(function(avatar) { var canvas = $('canvas'); var context = canvas.getContext('2d'); var x = Math.floor(Math.random() * canvas.width); var y = Math.floor(Math.random() * canvas.height); context.beginPath(); context.arc(x+24, y+24, 20, 0, Math.PI * 2, 1); context.clip(); context.strokeStyle = "black"; context.drawImage(document.getElementById(avatar.id), x, y); context.stroke(); }); Problem is, only the first image is drawn (or is visible). If I remove the clipping logic: $$('#avatars img').each(function(avatar) { var canvas = $('canvas'); var context = canvas.getContext('2d'); var x = Math.floor(Math.random() * canvas.width); var y = Math.floor(Math.random() * canvas.height); context.drawImage(document.getElementById(avatar.id), x, y); }); Then all my images are drawn. Is there a way to get each image individually clipped? I tried resetting the clipping area to be the entire canvas between images but that didn't work.

    Read the article

  • Manipulating / Resizing / Scaling an image in vb.net

    - by Christian Payne
    Imagine I have a rectangle say 400px x 300px. Then let’s say I want to load an image in that. All of this is very easy using Sytem.Drawing.DrawImage. But then I want to leave the left hand side as 300px but change the right hand side to 250 px. I can draw the box using 4 DrawLines but I don’t know how to squash the image into the new shape. I want the right hand side of the shape to be 250, the left size 300 and the top and bottom 400px. I can’t use DrawImage as it expects the left and right sizes to be the same. Is there a way to manipulate the image into the new shape? I've looked at other questions, but they only apply where the left and right hand side is equal. Any thoughts on how to squash an image into a shape which did not have parallel sides? (If it helps, I'm happy to sacrifice image quality to fit the right shape.)

    Read the article

  • Drawing an image is completely out

    - by ct2k7
    Hi I'm using this code below to let a user "draw" their signature on a UIView component on my app: UIGraphicsBeginImageContext(signature.frame.size); [drawImage.image drawInRect:CGRectMake(0, 0, signature.frame.size.width, signature.frame.size.height)]; CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0); CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0); CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); CGContextStrokePath(UIGraphicsGetCurrentContext()); CGContextFlush(UIGraphicsGetCurrentContext()); drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() The issue I am having is that the drawing is not only is the drawing not in line with the pointer when in use in the simulator, the image is going outside of the designated UIView compontent and is getting smaller/out of focus the more I draw, as you can see in this image: And after a few lines, showing the boundaries of the exact are of where I can draw: Any ideas on what's happening here? lastPoint.y is defined as: lastPoint.y -= 20; Any ideas on what on earth is happening here?

    Read the article

  • How to remove an object from the canvas?

    - by Marius Jonsson
    Hello there, I am making this script that will rotate a needle on a tachometer using canvas. I am a newbie to this canvas. This is my code: function startup() { var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var meter = new Image(); meter.src = 'background.png'; var pin = new Image(); pin.src = 'needle.png'; context.drawImage(meter,0,0); context.translate(275,297); for (var frm = 0; frm < 6000; frm++){ var r=frm/1000; //handle here var i=r*36-27; //angle of rotation from value of r and span var angleInRadians = 3.14159265 * i/180; //converting degree to radian context.rotate(angleInRadians); //rotating by angle context.drawImage(pin,-250,-3); //adjusting pin center at meter center } } Here is the script in action: http://www.kingoslo.com/instruments/ The problem is, as you can see, that the red needle is not removed beetween each for-loop. What I need to do is to clear the canvas for the pin object between each cycle of the loop. How do I do this? Thanks. Kind regards, Marius

    Read the article

  • JS: Why isn't this variable available to the other functions?

    - by Marius Jonsson
    Hello there, I've am trying to make a canvas animation: var context; var meter; var pin; function init() { var meter = new Image(); var pin = new Image(); var context = document.getElementById('canvas').getContext('2d'); meter.src = 'background.png'; pin.src = 'needle.png'; context.drawImage(meter,0,0); context.translate(275,297); context.save(); setTimeout(startup,500); } function startup() { var r=2; // set rpm here. var i=r*36-27; var angleInRadians = 3.14159265 * i/180; //converting degree to radian context.rotate(angleInRadians); //rotating by angle context.drawImage(pin,-250,-3); //adjusting pin center at meter center context.restore(); } You can see the script at http://www.kingoslo.com/instruments/ With firebug I get error saying that context is undefined, which I think is strange. Thanks. Kind regards, Marius

    Read the article

  • paintComponent on JPanel, image flashes and then disappears

    - by mark
    I have a JApplet (MainClass extends JApplet), a JPanel (ChartWindow extends JPanel) and a Grafico class. The problem is that the Grafico class instance has 2 JPanel that should show 2 images (1 for each panel) but the images are shown and after a little while they disappears: instead of them i get a gray background (like an empty JPanel). This happens for every repaint() call (that are made in the ChartWindow class) the MainClass init() contains chartwindow=new ChartWindow(); add(chartwindow) chartwindow has a Grafico instance. it's the ChartWindow's paintComponent (override) paintComponent(Graphics g) { super.paintComponent(g); Image immagineGrafico=createImage(grafico.pannelloGrafico.getWidth() ,grafico.pannelloGrafico.getHeight()); Image immagineVolumi=createImage(grafico.pannelloVolumi.getWidth() ,grafico.pannelloVolumi.getHeight()); Graphics2D imgGrafico=(Graphics2D)immagineGrafico.getGraphics(); Graphics2D imgVolumi=(Graphics2D)immagineVolumi.getGraphics(); grafico.draw(imgGrafico,imgVolumi,mouseX,mouseY); ((Graphics2D)grafico.pannelloGrafico.getGraphics()).drawImage(immagineGrafico,0,0,this); ((Graphics2D)grafico.pannelloVolumi.getGraphics()).drawImage(immagineVolumi,0,0,this); } grafico's JPanels are added this way in the ChartWindow's constructor grafico=new Grafico() ................ add(grafico.pannelloGrafico); add(grafico.pannelloVolumi); Tell me if you need more information, thank you very much :-)

    Read the article

  • C# image drawing colours are incorrect

    - by Jon Tackabury
    I have a source bitmap that is 1x1 and I am trying to take that image and draw it to a new bitmap. The source bitmap is all red, but for some reason the new bitmap ends up with a gradient (see image). Using the code below, shouldn't the new bitmap be completely red? Where is it getting the white/alpha from? private void DrawImage() { Bitmap bmpSOURCE = new Bitmap(1, 1, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmpSOURCE)) { g.Clear(Color.Red); } Bitmap bmpTest = new Bitmap(300, 100, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmpTest)) { g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.AssumeLinear; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PageUnit = GraphicsUnit.Pixel; g.PixelOffsetMode = PixelOffsetMode.None; g.SmoothingMode = SmoothingMode.None; Rectangle rectDest = new Rectangle(0, 0, bmpTest.Width, bmpTest.Height); Rectangle rectSource = new Rectangle(0, 0, 1, 1); g.DrawImage(bmpSOURCE, rectDest, rectSource, GraphicsUnit.Pixel); } pictureBox1.Image = bmpTest; }

    Read the article

  • .net Drawing.Graphics.FromImage() returns blank black image

    - by joox
    I'm trying to rescale uploaded jpeg in asp.net So I go: Image original = Image.FromStream(myPostedFile.InputStream); int w=original.Width, h=original.Height; using(Graphics g = Graphics.FromImage(original)) { g.ScaleTransform(0.5f, 0.5f); ... // e.g. using (Bitmap done = new Bitmap(w, h, g)) { done.Save( Server.MapPath(saveas), ImageFormat.Jpeg ); //saves blank black, though with correct width and height } } this saves a virgin black jpeg whatever file i give it. Though if i take input image stream immediately into done bitmap, it does recompress and save it fine, like: Image original = Image.FromStream(myPostedFile.InputStream); using (Bitmap done = new Bitmap(original)) { done.Save( Server.MapPath(saveas), ImageFormat.Jpeg ); } Do i have to make some magic with g? upd: i tried: Image original = Image.FromStream(fstream); int w=original.Width, h=original.Height; using(Bitmap b = new Bitmap(original)) //also tried new Bitmap(w,h) using (Graphics g = Graphics.FromImage(b)) { g.DrawImage(original, 0, 0, w, h); //also tried g.DrawImage(b, 0, 0, w, h) using (Bitmap done = new Bitmap(w, h, g)) { done.Save( Server.MapPath(saveas), ImageFormat.Jpeg ); } } same story - pure black of correct dimensions

    Read the article

  • Canvas draw calls are rendering out of sequence

    - by Tom Murray
    I have the following code for writing draw calls to a "back buffer" canvas, then placing those in a main canvas using drawImage. This is for optimization purposes and to ensure all images get placed in sequence. Before placing the buffer canvas on top of the main one, I'm using fillRect to create a dark-blue background on the main canvas. However, the blue background is rendering after the sprites. This is unexpected, as I am making its fillRect call first. Here is my code: render: function() { this.buffer.clearRect(0,0,this.w,this.h); this.context.fillStyle = "#000044"; this.context.fillRect(0,0,this.w,this.h); for (var i in this.renderQueue) { for (var ii = 0; ii < this.renderQueue[i].length; ii++) { sprite = this.renderQueue[i][ii]; // Draw it! this.buffer.fillStyle = "green"; this.buffer.fillRect(sprite.x, sprite.y, sprite.w, sprite.h); } } this.context.drawImage(this.bufferCanvas,0,0); } This also happens when I use fillRect on the buffer canvas, instead of the main one. Changing the globalCompositeOperation between 'source-over' and 'destination-over' (for both contexts) does nothing to change this. Paradoxically, if I instead place the blue fillRect inside the nested for loops with the other draw calls, it works as expected... Thanks in advance!

    Read the article

  • 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

  • JTable how to change BackGround Color

    - by mKorbel
    I inspired by MeBigFatGuy interesting question, in this conection I have very specific question about Graphisc2D, how to change BackGround Color by depends if is JTables Row visible in the JViewPort, 1) if 1st. & last JTables Row will be visible in the JViewPort, then BackGround would be colored to the Color.red 2) if 1st. & last JTables Row will not be visible in the JViewPort, then BackGround would be colored to the Color.whatever from SSCCE import java.awt.*; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import javax.swing.*; import javax.swing.RepaintManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.TableModel; /* http://stackoverflow.com/questions/1249278/ how-to-disable-the-default-painting-behaviour-of-wheel-scroll-event-on-jscrollpan * and * http://stackoverflow.com/questions/8195959/ swing-jtable-event-when-row-is-visible-or-when-scrolled-to-the-bottom */ public class ViewPortFlickering { private JFrame frame = new JFrame("Table"); private JViewport viewport = new JViewport(); private Rectangle RECT = new Rectangle(); private Rectangle RECT1 = new Rectangle(); private JTable table = new JTable(50, 3); private javax.swing.Timer timer; private int count = 0; public ViewPortFlickering() { GradientViewPort tableViewPort = new GradientViewPort(table); viewport = tableViewPort.getViewport(); viewport.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { RECT = table.getCellRect(0, 0, true); RECT1 = table.getCellRect(table.getRowCount() - 1, 0, true); Rectangle viewRect = viewport.getViewRect(); if (viewRect.intersects(RECT)) { System.out.println("Visible RECT -> " + RECT); } else if (viewRect.intersects(RECT1)) { System.out.println("Visible RECT1 -> " + RECT1); } else { // } } }); frame.add(tableViewPort); frame.setPreferredSize(new Dimension(600, 300)); frame.pack(); frame.setLocation(50, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RepaintManager.setCurrentManager(new RepaintManager() { @Override public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { Container con = c.getParent(); while (con instanceof JComponent) { if (!con.isVisible()) { return; } if (con instanceof GradientViewPort) { c = (JComponent) con; x = 0; y = 0; w = con.getWidth(); h = con.getHeight(); } con = con.getParent(); } super.addDirtyRegion(c, x, y, w, h); } }); frame.setVisible(true); start(); } private void start() { timer = new javax.swing.Timer(100, updateCol()); timer.start(); } public Action updateCol() { return new AbstractAction("text load action") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { System.out.println("updating row " + (count + 1)); TableModel model = table.getModel(); int cols = model.getColumnCount(); int row = 0; for (int j = 0; j < cols; j++) { row = count; table.changeSelection(row, 0, false, false); timer.setDelay(100); Object value = "row " + (count + 1) + " item " + (j + 1); model.setValueAt(value, count, j); } count++; if (count >= table.getRowCount()) { timer.stop(); table.changeSelection(0, 0, false, false); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { table.clearSelection(); } }); } } }; } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { ViewPortFlickering viewPortFlickering = new ViewPortFlickering(); } }); } } class GradientViewPort extends JScrollPane { private static final long serialVersionUID = 1L; private final int h = 50; private BufferedImage img = null; private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB); private JViewport viewPort; public GradientViewPort(JComponent com) { super(com); viewPort = this.getViewport(); viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE); viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE); Graphics2D g2 = shadow.createGraphics(); g2.setPaint(new Color(250, 150, 150)); g2.fillRect(0, 0, 1, h); g2.setComposite(AlphaComposite.DstIn); g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h, new Color(0.5f, 0.8f, 0.8f, 0.5f))); g2.fillRect(0, 0, 1, h); g2.dispose(); } @Override public void paint(Graphics g) { if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) { img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); } Graphics2D g2 = img.createGraphics(); super.paint(g2); Rectangle bounds = getViewport().getVisibleRect(); g2.scale(bounds.getWidth(), -1); int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight(); g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null); g2.scale(1, -1); g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null); g2.dispose(); g.drawImage(img, 0, 0, null); } }

    Read the article

  • How to edit item in a listbox shown from reading a .csv file?

    - by Shuvo
    I am working in a project where my application can open a .csv file and read data from it. The .csv file contains the latitude, longitude of places. The application reads data from the file shows it in a static map and display icon on the right places. The application can open multiple file at a time and it opens with a new tab every time. But I am having trouble in couple of cases When I am trying to add a new point to the .csv file opened. I am able to write new point on the same file instead adding a new point data to the existing its replacing others and writing the new point only. I cannot use selectedIndexChange event to perform edit option on the listbox and then save the file. Any direction would be great. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CourseworkExample { public partial class Form1 : Form { public GPSDataPoint gpsdp; List<GPSDataPoint> data; List<PictureBox> pictures; List<TabPage> tabs; public static int pn = 0; private TabPage currentComponent; private Bitmap bmp1; string[] symbols = { "hospital", "university" }; Image[] symbolImages; ListBox lb = new ListBox(); string name = ""; string path = ""; public Form1() { InitializeComponent(); data = new List<GPSDataPoint>(); pictures = new List<PictureBox>(); tabs = new List<TabPage>(); symbolImages = new Image[symbols.Length]; for (int i = 0; i < 2; i++) { string location = "data/" + symbols[i] + ".png"; symbolImages[i] = Image.FromFile(location); } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; lb.Width = 300; int selectedindex = lb.SelectedIndex; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); } } private void openToolStripMenuItem_Click_1(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; ListBox lb = new ListBox(); lb.Width = 300; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); MessageBox.Show(data.ToString()); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void addBtn_Click(object sender, EventArgs e) { string wayName = nameTxtBox.Text; float wayLat = Convert.ToSingle(latTxtBox.Text); float wayLong = Convert.ToSingle(longTxtBox.Text); float wayEle = Convert.ToSingle(elevTxtBox.Text); WayPoint wp = new WayPoint(wayName, wayLat, wayLong, wayEle); GPSDataPoint gdp = new GPSDataPoint(); data = new List<GPSDataPoint>(); gdp.Add(wp); lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); lb.Refresh(); StreamWriter sr = new StreamWriter(name); sr.Write(lb); sr.Close(); DialogResult result = MessageBox.Show("Save in New File?","Save", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = "default.csv"; DialogResult saveResult = saveDialog.ShowDialog(); if (saveResult == DialogResult.OK) { sr = new StreamWriter(saveDialog.FileName, true); sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } } else { // sr = new StreamWriter(name, true); // sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } MessageBox.Show(name + path); } } } GPSDataPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace CourseworkExample { public class GPSDataPoint { private float[] bounds; private List<WayPoint> dataList; public GPSDataPoint() { dataList = new List<WayPoint>(); } internal void setBounds(string p) { string[] b = p.Split(','); bounds = new float[b.Length]; for (int i = 0; i < b.Length; i++) { bounds[i] = Convert.ToSingle(b[i]); } } public float[] Bounds { get { return bounds; } } internal void addWaypoint(string s) { WayPoint wp = new WayPoint(s); dataList.Add(wp); } public WayPoint getWayPoint(int i) { if (i < dataList.Count) { return dataList[i]; } else return null; } public List<WayPoint> DataList { get { return dataList; } } internal void Add(WayPoint wp) { dataList.Add(wp); } } } WayPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CourseworkExample { public class WayPoint { private string name; private float ele; private float latitude; private float longitude; private string sym; public WayPoint(string name, float latitude, float longitude, float elevation) { this.name = name; this.latitude = latitude; this.longitude = longitude; this.ele = elevation; } public WayPoint() { name = "no name"; ele = 3.5F; latitude = 3.5F; longitude = 0.0F; sym = "no symbol"; } public WayPoint(string s) { string[] bits = s.Split(','); name = bits[0]; longitude = Convert.ToSingle(bits[2]); latitude = Convert.ToSingle(bits[1]); if (bits.Length > 4) sym = bits[4]; else sym = ""; try { ele = Convert.ToSingle(bits[3]); } catch (Exception e) { ele = 0.0f; } } public float Longitude { get { return longitude; } set { longitude = value; } } public float Latitude { get { return latitude; } set { latitude = value; } } public float Ele { get { return ele; } set { ele = value; } } public string Name { get { return name; } set { name = value; } } public string Sym { get { return sym; } set { sym = value; } } } } .csv file data birthplace.png 51.483788,-0.351906,51.460745,-0.302982 Born Here,51.473805,-0.32532,-,hospital Danced here,51,483805,-0.32532,-,hospital

    Read the article

  • Rotate an image in a scaled context

    - by nathan
    Here is my working piece of code to rotate an image toward a point (in my case, the mouse cursor). float dx = newx - ploc.x; float dy = newy - ploc.y; float angle = (float) Math.toDegrees(Math.atan2(dy, dx)); Where ploc is the location of the image i'm rotating. And here is the rendering code: g.rotate(loc.x + width / 2, loc.y + height / 2, angle); g.drawImage(frame, loc.x, loc.y); Where loc is the location of the image and "width" and "height" are respectively the width and height of the image. What changes are needed to make it works on a scaled context? e.g make it works with something like g.scale(sx, sy).

    Read the article

  • How to move an object using X and Y coordinates in JavaScript

    - by Geroy290
    I am making a 2d game with JavaScript and HTML5 and am trying to move an image that I have drawn with JavaScript like so: //canvas var c = document.getElementById("gameCanvas"); var ctx = c.getContext("2d"); //baseball var baseball = new Image(); baseball.onload = function() { ctx.drawImage(baseball, 400, 425); }; baseball.src = "baseball2.png"; I'm not sure how I would move it though, I have seen many people seem to just type something like ballX and ballY but I don't understand where the actual x and y definition comes from. Here is my code so far: http://jsfiddle.net/xRfua/ I have a different image source but it is a local source so I couldn't include it. Thanks in a dvance for any help!

    Read the article

  • HTML5 Game (Canvas) - UI Techniques?

    - by Jason L.
    Hi! I'm in the process of building a JavaScript / HTML5 game (using Canvas) for mobile (Android / iPhone/ WebOS) with PhoneGap. I'm currently trying to design out how the UI and playing board should be built and how they should interact but I'm not sure what the best solution is. Here's what I can think of - Build the UI right into the canvas using things like drawImage and fillText Build parts of the UI outside of the canvas using regular DOM objects and then float a div over the canvas when UI elements need to overlap the playing board canvas. Are there any other possible techniques I can use for building the game UI that I haven't thought of? Also, which of these would be considered the "standard" way (I know HTML5 games are not very popular so there probably isn't a "standard" way yet)? And finally, which way would YOU recommend / use? Many thanks in advance!

    Read the article

  • fast java2d translucency

    - by mdriesen
    I'm trying to draw a bunch of translucent circles on a Swing JComponent. This isn't exactly fast, and I was wondering if there is a way to speed it up. My custom JComponent has the following paintComponent method: public void paintComponent(Graphics g) { Rectangle view = g.getClipBounds(); VolatileImage image = createVolatileImage(view.width, view.height); Graphics2D buffer = image.createGraphics(); // translate to camera location buffer.translate(-cx, -cy); // renderables contains all currently visible objects for(Renderable r : renderables) { r.paint(buffer); } g.drawImage(image.getSnapshot(), view.x, view.y, this); } The paint method of my circles is as follows: public void paint(Graphics2D graphics) { graphics.setPaint(paint); graphics.fillOval(x, y, radius, radius); } The paint is just an rgba color with a < 255: Color(int r, int g, int b, int a) It works fast enough for opaque objects, but is there a simple way to speed this up for translucent ones?

    Read the article

  • ArgumentError: Error #2015: Invalid BitmapData.

    - by numerical25
    I am having problems loading a bitmapData. I am getting the following error Engine Init //trace loadimage//trace ArgumentError: Error #2015: Invalid BitmapData. at flash.display::BitmapData() Below is my code. it appears it happens after the trace loadimage package com.objects { import flash.display.Sprite; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Point; import flash.geom.Rectangle; import flash.display.Loader; import flash.net.URLRequest; import flash.net.*; import flash.events.*; import flash.display.LoaderInfo; public class gameObject extends Sprite { protected var w:Number; protected var h:Number; protected var image:BitmapData; protected var canvas:Bitmap; protected var px:Number; protected var py:Number; public function gameObject():void { init(); } private function init():void { } public function loadImage(imageDir:String, w:Number, h:Number, px:Number, py:Number):void { this.w = w; this.y = y; this.px = px; this.py = py; trace("loadimage"); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE,imageComplete); loader.load(new URLRequest(imageDir)); } private function imageComplete(e:Event):void { var loader:LoaderInfo = LoaderInfo(e.target); image = Bitmap(loader.content).bitmapData; drawImage(); } private function drawImage():void { var tilePoint:Point = new Point(0,0); var tileRect = new Rectangle(py,px,w,h); trace(loader.content); var canvasData:BitmapData = new BitmapData(w,h); trace("got canvas data"); canvasData.copyPixels(image,tileRect,tilePoint); trace("copied pixels"); canvas = new Bitmap(canvasData); } } } And my call the the method is like so balls = new Array(); balls[0] = new gameObject(); balls[0].loadImage("com/images/ball.gif", 15,15,0,0); When I trace the Loader.content, below is what shows Engine Init loadimage [object Bitmap] ArgumentError: Error #2015: Invalid BitmapData. at flash.display::BitmapData()

    Read the article

  • Java: Detecting image format, resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • Resized image degrades in quality.

    - by Venkats
    I resized an image using Java2D Graphics class. But it doesn't look right. BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null); g.dispose(); Is it possible to scale an image without introducing artifacts?

    Read the article

  • Java: Detecting image formate - resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >