Draw graphics on Image and Save it

hi!,
Can anyone help me how to draw graphics(Line, rectangle.ect) on an Image and save it. I need to do the following steps.
1. Get the Image from the local file system
2. Based on the parameters i receive for graphics(Ex: rectangle).
-I have to draw a rectangle on the Image.
3. Save the Image again to the file system
I would appreciate if any one has any ideas or sample code I can start with.
Thanks!!!

Here's an example using the javax.imageio package.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class DrawOnImage {
    public static void main(String[] args) {
        try {
            BufferedImage buffer = ImageIO.read(new File(args[0]));
            Graphics2D g2d = buffer.createGraphics();
            Rectangle rect = new Rectangle(10, 10, 100, 100);
            g2d.setPaint(Color.RED);
            g2d.draw(rect);
            ImageIO.write(buffer, "JPG", new File(args[1]));
        } catch (IOException e) {
            e.printStackTrace();
}

Similar Messages

  • How do I take an object from an image and save it so I can use it in other images?

    I am trying to figure out how to take an object from an image and save it so I can re-use it again in other pictures?  I know how to use the magic wand to select the object and place it in a blank image.... but I do not know how to re size the selected object or keep it for later use.  Basically I would like to use the object the same way that I use the graphics ... so I guess I am wondering if there is a way that I can make my own graphics... I have Elements Photoshop 13.  Thanks for any help/advice....  Jerrie

    Hi Jerrie,
    You can re-size using Transformation tool. Ctrl + T will give you a box to re-size the image or object.
    You can save these object as PNG file with Transparent layer. You can use these objects later in another projects.
    Regards,
    Sandeep

  • SuperImpose two images and save it as a single image[urgent]

    Hello..
    Can anyone tell me how do we superimpose two images and save it as a single image.The image on the top is smaller in size in my case.
    Please Help..

    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    class TwoBecomeOne {
        public static void main(String[] args) throws IOException {
            BufferedImage large = ImageIO.read(new File("images/tiger.jpg"));
            BufferedImage small = ImageIO.read(new File("images/bclynx.jpg"));
            int w = large.getWidth();
            int h = large.getHeight();
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.drawImage(large, 0, 0, null);
            g2.drawImage(small, 10, 10, null);
            g2.dispose();
            ImageIO.write(image, "jpg", new File("twoInOne.jpg"));
            JOptionPane.showMessageDialog(null, new ImageIcon(image), "",
                                          JOptionPane.PLAIN_MESSAGE);
    }

  • AppleScript to resize images and save with new name

    I want to make an apple script, which resizes all images of a folder regardless what kind of filetype.
    The source folder will change every day.
    With the script i want to choose a source Folder, resize all images and save the files with my jpeg options in the same folder, but with adding  „_ipad“ in the filename.
    I tried to edit an existing script from this forum, but in Photoshop 5.1 i get the error-message "This function is possibly not available in this Version" in line 18 "save in file newFileName as JPEG with options myOptions"
    How can i save the documents with new name in the existing folder?
    Thanks.
    This is the script i’m working with:
    set inputFolder to choose folder with prompt "Wähle einen Ordner:"
    --set destinationFolder to choose folder with prompt "Wähle einen Zielordner" as string
    tell application "Finder"
              set filesList to (files of entire contents of inputFolder) as alias list
    end tell
    tell application "Adobe Photoshop CS5.1"
              set UserPrefs to properties of settings
              set ruler units of settings to pixel units
              repeat with aFile in filesList
      open aFile showing dialogs never
                        set docRef to the current document
                        tell docRef
                                  set newFileName to my getBaseName(name)
      --resize image height 240 resolution 72 resample method bicubic sharper
      change mode to RGB
      resize image resolution 72
                                  set myOptions to {class:JPEG save options, embed color profile:true, quality:12, format options:progressive, scans:3}
      save in file newFileName as JPEG with options myOptions
                        end tell
      close the current document saving no
              end repeat
              set ruler units of settings to ruler units of UserPrefs
    end tell
    on getBaseName(fName)
              set baseName to fName
              repeat with idx from 1 to (length of fName)
                        if (item idx of fName = ".") then
                                  set baseName to (items 1 thru (idx - 1) of fName) as string
                                  exit repeat
                        end if
              end repeat
              return baseName
    end getBaseName

    This seems like a Photoshop error not an AppleScript one. Have you looked in the Photoshop dictionary to see if the command you are getting the error on exists and if it has those options?
    If all you want to do is resize image files and save the resized image file you might want to look at Automator. Specifically the Scale Image action under Photos.
    regards

  • Trying to create an image and save it on file system

    Hi,
    I'm trying to create an image and save it in the file system :
         public static void main(String[] args) {
         int wid = 632;
         int hgt = 864;
         BufferedImage bufferedImage = new BufferedImage(wid,hgt,BufferedImage.TYPE_INT_RGB);
         bufferedImage.getGraphics().setColor(Color.black);
         bufferedImage.getGraphics().drawOval(30, 30, 100, 100);
              bufferedImage.getGraphics().drawString("test me one two three",2,2);
              bufferedImage.flush();
    try {
                   ImageIO.write(bufferedImage,".bmp",new File("C:/MyImage.bmp"));
         } catch (IOException e) {               
                   e.printStackTrace();
    THE PROBLEM : It creates C:/MyImage.bmp on my file system, but the file is empty (size 0).
    Am I missing something ?
    Thanks

    Try changing ".bmp" to "bmp". If that fails, try posting an SSCCE.
    Edit 1:
    And in future, please use the code tags when posting code, code snippets, HTML/XML or input/output. To do that, select the code and click the CODE button seen on the Plain Text tab of the message posting form.
    Edited by: AndrewThompson64 on Aug 3, 2009 1:23 AM

  • How to scan with capture image and save 10.6.8

    how to scan with capture image and save 10.6.8 ?

    Instructions for using Image Capture for this available via the 2nd section.
    http://support.apple.com/kb/HT2502

  • Trying to overlay text onto images and save them.

    What I want: I have a computer running the media in my car and I want to hook up a camera to it that'll record when the computer is running and overlay the GPS speed onto the video for later viewing.
    What I got: I have the following piece of code that saves a series of .jpg images at a specified frame rate and a separate Java application that puts them together into a .mov file to view later. I couldn't find anything to record the straight video so if you have any links for that, please point me. But for now I'll settle for doing it this way and I'm not too concerned with the GPS speed NMEA parsing for now, I'll just use a static speed label until I get the overlaying working.
    What I need: I need to know what to plug into the speedOverlay() method in order to grab the image and put the speed on top of it before saving it and moving to the next image. Any ideas?
    Code:
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import com.sun.media.sound.Toolkit;
    import javax.imageio.ImageIO;
    import javax.media.*;
    import javax.media.control.FrameGrabbingControl;
    import javax.media.format.VideoFormat;
    import javax.media.util.BufferToImage;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Panel;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.font.TextLayout;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Timer;
    import java.util.TimerTask;
    public class SwingCapture1 extends Panel implements Runnable, ActionListener
         private static final long serialVersionUID = 1L;
         public static Player player = null;
         public CaptureDeviceInfo di = null;
         public MediaLocator ml = null;
         public JButton start = new JButton("START");
         public JButton stop = new JButton ("STOP NOW");
         public JLabel frequencyLabel = new JLabel("Frequency:");
         public JTextField frequencyInputField = new JTextField(5);
         public JLabel framerateLabel = new JLabel("Framerate: ");
         public JTextField framerateInputField = new JTextField(5);
         public JLabel timerLabel = new JLabel("Timer: ");
         public JTextField timerInputField = new JTextField(5);
         public JPanel southPanel = new JPanel();
         public static Buffer buf = null;
         public static Image img = null;
         public VideoFormat vf = null;
         public static BufferToImage btoi = null;
         public static ImagePanel imgpanel = null;
         public static Timer timer = new Timer();
         static int theFrameRate = 0;
         static int theTimeLength = 0;
         static int i = 0;
         static int interval = 0;
         int count = 0;
         static int timeLength = 0;
         static String filePrefix = "";
         static String imagesDirectory = "c:\\images\\";
         static boolean timerBoolean = true;
         Thread capThread;
         Toolkit toolkit;
         public SwingCapture1()
              setLayout(new BorderLayout());
    //          setSize(640, 480);
              imgpanel = new ImagePanel();
              start.addActionListener(this);
              final String str = "vfw:Microsoft WDM Image Capture (Win32):0";
              di = CaptureDeviceManager.getDevice(str);
              ml = new MediaLocator(str);
              try
                   player = Manager.createRealizedPlayer(ml);
                   player.start();
                   Component comp;
                   if ((comp = player.getVisualComponent()) != null)
                        add(comp, BorderLayout.LINE_START);
    //               add(capture);
                   add(imgpanel, BorderLayout.LINE_END);
                   add(southPanel, BorderLayout.SOUTH);
                   southPanel.add(framerateLabel);
                   southPanel.add(framerateInputField);
                   southPanel.add(timerLabel);
                   southPanel.add(timerInputField);
                   southPanel.add(start);
                   southPanel.add(stop);
              catch (final Exception e)
                   System.out.println("ERROR 1");
                   e.printStackTrace();
         public static void playerclose()
              player.close();
              player.deallocate();
         public void actionPerformed(final ActionEvent e)
              final JComponent c = (JComponent) e.getSource();
              if (c == start)
    //               snapPicture();
                   theFrameRate = Integer.parseInt(framerateInputField.getText());
                   theTimeLength = Integer.parseInt(timerInputField.getText());
                   startCapture(theFrameRate, theTimeLength);
              if (c == stop)
                   timerBoolean = false;
         public void startCapture(final int framerate, final int timeLength)
              interval = 1000 / framerate;
              // Start timer.
              timer.scheduleAtFixedRate(new TimerTask ()
                   public void run()
                        System.out.println("SNAP");
                        snapPicture();
                        count++;
                        if (count >= timeLength * framerate)
                             this.cancel();
              }, 1000, interval);
         public static void snapPicture()
              final 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:\\java\\Tomcat\\webapps\\loadimage\\main.jpg");
              i++;
              speedOverlay(img);
              saveJPG(img, imagesDirectory + filePrefix + i + ".jpg");
         public static void speedOverlay(Image img)
         public static void saveJPG(final Image img, final String s)
              final BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
              final Graphics2D g2 = bi.createGraphics();
              g2.drawImage(img, null, null);
              FileOutputStream out = null;
              try
                   out = new FileOutputStream(s);
              catch (final java.io.FileNotFoundException io)
                   System.out.println("ERROR 2");
                   System.out.println("File Not Found");
              final JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              final JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
              param.setQuality(0.5f, false);
              encoder.setJPEGEncodeParam(param);
              try
                   encoder.encode(bi);
                   out.close();
              catch (final java.io.IOException io)
                   System.out.println("ERROR 3");
                   System.out.println("IOException");
         public void start()
              if (capThread == null)
                   capThread = new Thread(this, "Capture Thread");
                   capThread.start();
         public Image getFrameImage()
              // Grab a frame
              final FrameGrabbingControl fgc = (FrameGrabbingControl)
              player.getControl("javax.media.control.FrameGrabbingControl");
              buf = fgc.grabFrame();
              // Convert it to an image
              btoi = new BufferToImage((VideoFormat)buf.getFormat());
              return btoi.createImage(buf);
         @Override
         public void run() {
              // TODO Auto-generated method stub
    }

    Sorry guys, I haven't looked at your links yet but I will, once I get some time to sit down and code again. I just wanted to provide this piece of code that uses the Graphics2d you're talking about to overlay text onto an image but I haven't been able to plug it into my code at all. If you're links answer the question, I'm sorry, just providing it until I can actually sit down and spend time on the research you've given me. Thanks.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class WaterMark {
        public static void main(String[] args) throws IOException {
             String speed = "50";
            URL url = new URL("file:c:\\images\\1.jpg");
            BufferedImage im = ImageIO.read(url);
            String text = speed + " Km/H";
            Graphics2D g = im.createGraphics();
    //        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    //        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    //        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setFont(new Font("Lucida Bright", Font.ITALIC, 40));
    //        g.rotate(-Math.PI/4, im.getWidth()/2, im.getHeight()/2);
            TextLayout tl = new TextLayout(text, g.getFont(), g.getFontRenderContext());
    //        Rectangle2D bounds = tl.getBounds();
    //        double x = (im.getWidth()-bounds.getWidth())/2 - bounds.getX();
    //        double y = (im.getHeight()-bounds.getHeight())/2 - bounds.getY();
            double x = 10;
            double y = 50;
            Shape outline = tl.getOutline(AffineTransform.getTranslateInstance(x+2, y+1));
    //        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
            g.setPaint(Color.BLACK);
            g.draw(outline);
    //        g.setPaint(new GradientPaint(0, 0, Color.WHITE, 30, 20, new Color(128,128,255), true));
            tl.draw(g, (float)x, (float)y);
            g.dispose();
            display(im);
        public static void display(BufferedImage image) {
            JFrame f = new JFrame("WaterMark");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JLabel(new ImageIcon(image)));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • How to capture an image and save it using action script

    Hello,
    I need to know if is posible to capture an image or a screen region and save it using action scrip.
    Somebody know how to do it ??
    Thanks

    you can capture an image using the bitmapdata class and getPixel().  you can then save that to a bitmap using server-side code like php.

  • Looking to create script(s) that open a folder of image and save as each image is edited/retouched.

    I used to use the iOpener plug-in to read a folder of images and present each image to me to edit/retouch.  When I was done with the image, I clicked a button on a panel and it saved the resulting PSD in a designated destination folder and automagically retrieved the next image in the folder.  Do this repeatedly until all images in the folder were processed.  Fundy had a nice tool (Batch Editor), but it is end-of-life and not being offered anymore and iOpener seems to no longer be maintained.  Target app is Photoshop CS6 / CC.
    I want to build a simple set of scripts, embedded in a panel, that would let me replicate the basic function of these tools.  Open an image from a selected folder.  Let me do all the edits I want.  Then save the result to a designated destination folder (or just a Save and Close), the serve up the next image. 
    I have many years of software development in other languages, but relatively new to adobe scripting so am looking for example code to get me heading the right direction.  Also doesn't hurt to know whether something like this already exists and I can just use it.
    Thanks!
    -Mike Price
    Fairfield Photography

    PERFECT!!!!!!
    This is exactly what I was going to build.  No need to create when it is already done.
    Thank you very much.
    -Mike

  • How to transfer a 2D array from NI-scop into a gray scale image and save it

    Dear all,
    I acquired a 2D array and want to transfer it into a gray scale image (12 bits) and save it into my hard disk but I don't know how to do it.
    I can use Intensity graph to show the 2Darray into gray scale image, but the intensity graph.vi can not save the image in real time.
    Thank you.
    Solved!
    Go to Solution.

    The 24-bit is a color image with 8-bits per color channel per pixel (interleaved, if I remember correctly).  It is not a 24-bit gray-level, so I don't think it will work for you.  I believe the IMAQ library (a LabVIEW add-on) will handle 16-bit gray-scale, if you can get a copy.
    As a native LabVIEW workaround, you could also split your image into two 8-bit images, with one image representing the high bytes, the other the low.  You could then combine them when you do the analysis, if your analysis program is capable of this.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Load png image and save it

    I am loading a png file and saving it again with following code. The newly created image file is smaller size and poorer quality. How can I retain size and quality of the image?
    ===========================================
    File input = new File(imgFilePath+"img1.png");
    BufferedImage im = ImageIO.read(input);
    Graphics2D g = im.createGraphics();
    File output = new File(imgFilePath+"out2.png");
    ImageIO.write(im,"png",output);
    ===========================================

    Would a moderator please change this topic back to not solved.
    @Noel: I tried exactly what you said, copying the image to itself so the source and target would be the same size.  It does not work.  I do understand that you respond to many posts and can't actually try to reproduce every issue.   However, in this case, if you did try it on the posted image you would see that the problem is as I described it.
    @Acidiclnk: Thank you for reproducing the problem. Unfortunately, I checked your response as the correct answer, but now realize that it does not solve the problem. What you suggest shifts the position of the image from its as loaded position.  Then, as you said, copied images do register with the original.  The problem is, the shifted image no longer lines up with the other maps of my texture.
    It took me awhile to find the commands you described, as they are a bit different in my CS4 ("Align Layers to Selection > Vertical Centers", etc).  When I tried them, the pasted image was correctly registered with the original.  Unfortunately, as I mentioned, the image is no longer aligned with the other maps of the texture.
    For this particular case, since there were large, uniform areas in the image, I temporarily added fiducial marks to the problem image and one of the other maps.  Then, after copy/paste, I moved the shifted copy until it's fiducial was aligned with the other map, then removed the fiducals.  (I could not use MTSTUNER's Duplicate Layer suggestion, since duplicating it to a new image created a new image with the same problem as the original).
    To summarize: PhotoShop loads this image in one position, but aligning the centers or copy/paste moves it to another position.  I would be happy to know why this is so.  I did verfy that it's unique to PhotoShop as copy/paste works without the shift in another graphic editor.  Any insights would be welcome.

  • Auto align images and save them individually

    Is there a way to let photoshop auto align images and then save them to separate .tiff files?
    Best regards

    File > Scripts > Export Layers to Files
    Don't forget to crop the auto aligned imaged so that all layers share the same outline.

  • Cut a image and save each tile to a gif

    Hi
    Is it possible to cut a image which contain a lot of 24x24 tiles little image,
    then save each tile to gif or png?
    I whole like to build a map editor. with this function.
    Thanks

    Hi,
    Yes, it is possible.
    You can cut your image thanks to getSubImage (in BufferedImage class).
    About encoding and saving your tiles, take a look at http://www.geocities.com/marcoschmidt.geo/java-image-coding.html
    I hope it could help you.
    Stephane.

  • Update images and save

    Hi I was wondering if any one knew how i would be able to get images to update on open by using a javascript?
    I have the javascript below that I have been trying to modify, that opens a single indesign file and saves it with modified images update. My only problem is that in will not do more than one file. If there are multiple  files in a folder it will only update the images in the first indesign file it finds. Is there a way to modify this script to update all the indesign files it finds in a folder? Any assistance you can offer with this problem would be greatly appreciated
    Thank you very much
    if($error == null)
            try {
                    var theLinks = app.documents[0].links;
                    for (var i = 0; i < theLinks.length; i++)
                            theLinks[0].update();
            catch(theError) {
                    app.documents[0].close(SaveOptions.no);
                    $error = theError.description;

    This traverses through all the files with extension indd in the folder you specify. You can write your code that opens the specified file in the for loop in the end
    fold = new Folder(" folderPath here")
    allFiles = fold.getFiles("*.indd")
    for(i=0;i<allFiles.length;i++)
            //write your function here

  • Cut an image and save each tile to a gif or png

    Hi
    Is it possible to cut a image which contain a lot of 24x24 tiles little image,
    then save each tile to gif or png?
    I whole like to build a map editor. with this function.
    Thanks

    The problem is save seach tile to gif or png.
    I know how to cut the image.
    thanks

Maybe you are looking for

  • Dynamic SQL and IN CLAUSE from Pro C code

    Hi Guys, Tyring to embed sql in Pro C. Here I don't know in hand how many items will be there in the IN Clause of my dynamic sql. Tried this with a loop and then adding actual values to the stement and then executing it. This worked but as this hard

  • BAPI_GOODSMVT_CREATE Material Document Posting against Process Order

    Dear Experts,                     I want to post more than one documents from BAPI "BAPI_GOODSMVT_CREATE". It is working fine for GR(gmcode = 02) 101 Mvt. type. But the problem is that when there is a GI (gmcode = 03), serial numbers document comes;

  • PDF of Project File adds lines to the bottom

    When doing a PDF of a Microsoft 2007 project file, the PDF version has a bunch of lines added to the bottom. When printing the project file to a printer, these lines do not show up at all. I have tried it both in Std and Pro with the same results. So

  • Integrating existing file server with EP6SP9

    hello everyone we are implementing EP6 SP9 portal for our SBU and we need to integrate our existing file server with portal in which we can upload documents and download existing documents. do we need to use content management to access this file ser

  • Bind variable inside a package

    Can we declare a bind variable inside a package specification? CREATE OR REPLACE PACKAGE GET_EMPLOYEEDETAILS IS PROCEDURE GET_FIRSTNAME(E_ID IN EMPLOYEES.EMPLOYEE_ID%TYPE, F_NAME OUT EMPLOYEES.FIRST_NAME%TYPE); VARIABLE O VARCHAR2(20); END GET_EMPLOY