Servlet to generate JPG/GIF image

I've got sth like that:
response.setContentType("image/gif");
OutputStream out = response.getOutputStream();
Image messageImage = makeMessageImage(message, fontName, fontSize);What I should do next to send it to the browser and display it?

You can create a BufferedImage, draw messageImage onto it, and then send the BufferedImage through the OutputStream via
ImageIO.write(theBufferedImage, "gif", out); Or if messageImage is already a BufferedImage, then you can just send it directly after casting it.
There's a slight complication, however. The GIF format uses palette-based images. If you send an image that's not palette-based then it will use the default palette. It's the same as if I had created this
BufferedImage theBufferedImage = new BufferedImage(
        messageImage.getWidth(null),
        messageImage.getHeight(null),
        BufferedImage.TYPE_BYTE_INDEXED); drew messageImage onto it and then sent it. The default palette almost certainly isn't the 256 most representative colors in your message image. This may or may not be a problem. I don't know the kind of quality you want. If your image doesn't have any color, a viable alternative is TYPE_BYTE_GRAY.
Ideally, for a full-colored image you would create an IndexColorModel of what you feel is the 256 most representative colors in the image. Then you would create a BufferedImage using this palette, draw the original image onto it, and send it off.

Similar Messages

  • Links in JPG & GIF images.

    Hello board,
    I'm making some JPGs & animated GIFs for my website, and my CMS allows images to link to only a single link; e.g. it
    links the whole image.  Is it possible to embed multiple links in a single image THEN upload to one's CMS?  If so, how?

    Marian Driscoll wrote:
    JPG and GIF image files cannot contain even a single link. Links are only made through HTML.
    You can slice the image (see Photoshop help on 'slicing') and then apply unique links to each slice in the CMS' WYSIWYG editor.
    You can also manually enter a HTML image map for a single image file if your CMS allows raw HTML and does not filter that type of input.
    Or you can use Dreamweaver.

  • Mail converts jpg/gif images to tiff

    I have a friend who has an ibook running panther. When she tries to forward an email message that contains jpg or gif attachments, Mail converts them to tiff, which causes problems for her windows bound friends, and also increases the message size by a factor of 10. Animated gif attachments converted to tif are useless.
    Is there any way for her to stop Mail from converting these attachments to tif? Thanks.

    Is there any way for her to stop Mail from converting these attachments to tif?
    Not with Jaguar or Panther Mail.
    This is caused by the sender using HTML for message composition and a jpg or gif being embedded in the message body which are not true attachments.
    Jaguar and Panther Mail render HTML received but do not support composing in HTML which includes when forwarding a message received that was composed in HTML. Jaguar/Panther Mail supports RTF and Plain Text only so when forwarding a message received that was composed in HTML with embedded images, the Mail.app converts the embedded images to attachments and uses RTF.
    Although Tiger Mail does not support complex HTML composition within the body of a message, RTF in Tiger Mail is HTML. Tiger Mail also supports forwarding a received message that was composed in HTML. With Safari under Tiger, you can select Mail Contents of This Page which will copy the selected web page and paste the contents in a new mail message and the contents of the copied web page will be sent in it's entirety.

  • I got ArrayIndexOutOfBoundsException when I tried to generate the gif image

    I just upgrade JDK from 1.5 to 1.6. Then I want to save my image as a gif file. ( I used to save it as png file which was working perfect. ). I got ArrayIndexOutOfBoundsException at the time I am trying to save the image file:
    java.lang.ArrayIndexOutOfBoundsException: 0
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:267)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.insertNode(PaletteBuilder.java:274)
    at com.sun.imageio.plugins.common.PaletteBuilder.buildPalette(PaletteBuilder.java:237)
    at com.sun.imageio.plugins.common.PaletteBuilder.createIndexedImage(PaletteBuilder.java:76)
    at com.sun.imageio.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:564)
    at com.sun.imageio.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:492)
    at javax.imageio.ImageWriter.write(ImageWriter.java:598)
    at javax.imageio.ImageIO.write(ImageIO.java:1479)
    at javax.imageio.ImageIO.write(ImageIO.java:1521)
    at xxx.xxx.xxx.clusterImage.ClusterImageMaker.saveImage(ClusterImageMaker.java:863)
    The code that caused exception in ClusterImageMaker.java is as following:
    try {
    857 //if (!imageExist(atrgtr, list)) {
    858 //return;
    859 //}
    860 String gifname = findImageFileName( atrgtr, somNum,list);
    861 String fullname = gifpath + gifname;
    862 log.info("file name = " + fullname);
    863 ImageIO.write(im_out, "GIF", new File( fullname ));
    864 } catch (Exception ex) {
    865 log.error("error" + ex.getMessage());
    866 ex.printStackTrace();
    867 throw new SMDException( "fail to save image file ", ex );
    868 }
    It took me quite a time trying to figure it out. Now I am desperate. Please help.

    Post a SSCCE .

  • How desactivate the smooth for jpg,gif images¿?

    Hi
    I need view the images pixelates...no smoothing...
    because in others computers with out Geforce card, show pixelate.
    Driver 4403
    Windows XP
    How desactivate the smooth images¿?...

    Sorry...my english is terrible
    i zoom in the image but the video card smooth the image...and i cant see the real state of the image...if stay pixelate or not...always smooth....how desactivate this option in my video card

  • Color .jpg/.gif images in the .CHM and true (4BPP/8BPP) grayscale in Printed Output?

    I do all my document creation in RH first, then output
    WinHelp and to Word 2003. I want to keep color images in the CHM
    and have a majority of the images become true monochrome grayscale
    in the Word doc.
    Yes, Word does have a nifty "grayscale" optopn for each
    image, but it leaves the color "channels" (24BPP) and so our color
    copier still prints page using all CYMK colors (and it never seems
    to get "true" grays anyway...)
    If I could somehow get monochrome grayscale images in RH,
    where there is already color ones - I could save as "monochrome"
    and "color" outputs.
    Any ideas, hints, batch files, suggestions or comments?
    Thank you!

    On second thought... it's the Fiery controller in the copier
    that's doing all the deciding on what's what, and unfortunately
    "that's not my department", so at this point, the question here is
    moot - it's not a RH issue.

  • PLEASE HELP!!! using servlet to generate an image in jsp page

    Hi,
    I am so stuck on this... please help.
    I have a servlet that generated a gif image dynamically. It uses a bean that stores the gif image in a byte array.
    The servlet outputs the byte data to the output stream. The code is really simple and looks like this:
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //HttpSession session = request.getSession();
            try {
                ServletOutputStream stream = response.getOutputStream();
                ImageByteInformation imageByteInfo = (ImageByteInformation) request.getAttribute("imageByteInformation");
                response.setContentType("image/gif");
                response.setContentLength(imageByteInfo.getByteData().length);
                stream.write(imageByteInfo.getByteData(), 0, imageByteInfo.getByteData().length);
                stream.flush();
            }catch( Exception e){   
                System.out.println("You are hooped!: " + e.getMessage() + " " + e.toString());           
            }When I redirect from the dispatch servlet straight to this servlet an image shows up in the browser window.
    However when I try to use this jsp page to display the image nothing happens...
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h2>Hello World!</h2>
            <img src="servlets/Map24ImageDisplayServlet"/>
             //I also tried src/servlets/Map24..., /src/servlets/Map24..., /display, servlets/display
            <h2>Did you see the image?</h2>
        </body>
    </html>My web.xml is here if it helps...
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name>HelloProject</display-name>
    <servlet>
        <display-name>ServletDispatcher</display-name>
        <servlet-name>ServletDispatcher</servlet-name>
        <servlet-class>servlets.ServletDispatcher</servlet-class>
      </servlet>
      <servlet>
        <display-name>Map24ImageDisplayServlet</display-name>
        <servlet-name>Map24ImageDisplayServlet</servlet-name>
        <servlet-class>servlets.Map24ImageDisplayServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>ServletDispatcher</servlet-name>
        <url-pattern>/hello</url-pattern>
      </servlet-mapping>
      <error-page>
        <error-code>404</error-code>
        <location>/404_error.html</location>
      </error-page>
      <servlet-mapping>
        <servlet-name>Map24ImageDisplayServlet</servlet-name>
        <url-pattern>/display</url-pattern>
      </servlet-mapping>
    </web-app>I can never get an image to come up. In fact I can never get the jsp page to run the servlet at all! HELP!!! What am I doing wrong?
    Thanks
    Edited by: Kind_of_Green on May 5, 2008 3:55 PM
    Edited by: Kind_of_Green on May 5, 2008 4:00 PM

    OK... so you WERE absolutely right about the src path for the image tag.
    However I also had another problem that was quite a bit more insidious and mostly just a symptom
    of how little I know about what goes on under the hood of a web app.
    My bean storing the image info was stored as a request attribute. When the servlet was called from the
    jsp page the request object was either reset or just never initialized. Anyway it is not the same request
    object I assumed it was being passed in the doGet method. I added my bean as a session
    attribute and everything is sparkly :)
    I can only assume that when a request is neither forwarded nor included (as is the case with
    calling the servlet from the img tag) it is disappeared.
    Anyway, thanks a mint man. I so totally appreciate your time.
    Ciao :)

  • Cannot edit JPG, GIF files stored in a SharePoint 2010 picture library

    Created a SharePoint 2010 picture library to store .jpg, .gif images along with other types of images which were created using Adobe photoshop, Tiff etc.
    Upon clicking on the .jpg, .gif files for editing purposes, they open in the browser instead of Photoshop so I cannot edit these files for this reason. Other types of image files are editable but not the jpg, gif files. File associations are already
    in place for these files to open in Photoshop. Please advise.
    Thank you,
    Mahesh

    You can change the default application that opens while you click open document using DocIcon.xml which is present on the web front ends. Please look at this link which explains what you need to update in order to take care of your requirement. 
    http://msdn.microsoft.com/en-us/library/ms463701.aspx
    Hope this helps. 
    Thanks, Mayur Joshi Blog: http://splearnings.blogspot.com/

  • Converting GIF images to JPG - display problems in browser

    I am currently writing a program that uses the ImageIO package (javax.imageio.*) to take GIF and PNG images and convert them to JPG images. The program seems to convert them correctly, especially for the PNG images, but the converted GIF images don't open in a browser. They open just fine in Windows Picture and Fax viewer, but when I try to open them in IE or Firefox, it only diplays the little red 'x'.
    Is anyone familiar enough with Images and the ImageIO package in Java that they may have some insight on why these converted GIF files won't display in a browser.

    Bonjour,
    In my [website|http://iweb.debutersurmac.com>, all the images are JPG files,
    By default iWeb '09 converts images to JPG (yes, it's true)...
    ...unless you use masked images*
    !http://i32.servimg.com/u/f32/09/02/44/99/masked10.jpg!
    Crop your images (with Preview) before you paste them in iWeb. Don't use mask, Unmask an image if it's masked. That's the trick!
    !http://i32.servimg.com/u/f32/09/02/44/99/unmask10.jpg!
    (* images with transparency areas (ex : some PNG and GIF), rotation and shapes in iWeb make also PNG files in your website.)

  • Gif images in pdf file generated from Reports 6i

    Hello,
    When I generate pdf file from Reports Builder 6i and open this file with Acrobat Reader 5.0 I get that some of my gifs are black or other color.
    When I generate the same report to the live previewer everything is OK.
    Is it a Reports 6i bug? Any workarounds?
    Best regards
    Raimundas Katilius

    Hi
    If u generate the report output to PDF from the report
    GIF images doesn't show up properly . Generate it from the
    application then i think it will print clearly.
    If u try to print text followed by image and followed by text
    again PDF will not print
    I think this should help u
    Sri
    Hello,
    When I generate pdf file from Reports Builder 6i and open this file with Acrobat Reader 5.0 I get that some of my gifs are black or other color.
    When I generate the same report to the live previewer everything is OK.
    Is it a Reports 6i bug? Any workarounds?
    Best regards
    Raimundas Katilius

  • ITunes converts all my GIF images to JPG when I sync my iPhone.

    I have an iPhone and a Mac, and on my iPhone I have noticed that whenever I preview my images, GIF images won't play. They will just sit there, and I can only see one frame of them. I have to send the GIFs to myself through text to see them play, but they are GIF files on my iPhone. But, the recent images that I have downloaded from my iTunes to my iPhone do not show up as GIFs, they show up as JPGs instead. Everytime I sync my photos, the GIFs just randomly get converted into JPG images on my iPhone, and I'm not sure how to stop it from doing that. I don't know any other way to move my images from my Mac onto my iPhone without going through iTunes to do so. Is there a way I can get it to stop converting them to JPGs, or is there another way to put photos from my Mac to my iPhone? Thanks!

    I have an iPhone and a Mac, and on my iPhone I have noticed that whenever I preview my images, GIF images won't play. They will just sit there, and I can only see one frame of them. I have to send the GIFs to myself through text to see them play, but they are GIF files on my iPhone. But, the recent images that I have downloaded from my iTunes to my iPhone do not show up as GIFs, they show up as JPGs instead. Everytime I sync my photos, the GIFs just randomly get converted into JPG images on my iPhone, and I'm not sure how to stop it from doing that. I don't know any other way to move my images from my Mac onto my iPhone without going through iTunes to do so. Is there a way I can get it to stop converting them to JPGs, or is there another way to put photos from my Mac to my iPhone? Thanks!

  • How JPG or GIF Image open in MIDP?

    How my j2me application can support jpg or gif image format. I have tested png file in midp 1.0 and its not support other than png format( im not sure about midp 2.0 does it support or not). I have seen lot of mobiles those support gif and jpg file formats. Does j2me applications on those mobile can support other image formats?
    Plus it is possible that i can develop my own decoder for jpg or gif format. I know it possible, but im talking related to its processing power consumption. Or is there any third party api exist to support jpg or gif file format on midp. Please r

    Here is the code snap that read image from a URL.. I have tested this code on localhost & two different pc on lan in emulator.. but not in actuall mobile... but i hope it will work...
    Image image = null ;
    DataInputStream httpInput = null ;
    DataOutputStream httpOutput = null ;
    HttpConnection httpCon = null ;
    String url = "http://localhost:8080/images/picture.png"
    try
    httpCon = (HttpConnection)Connector.open(url);
    int bufferSize = 512 ;
         byte byteInput[] = new byte[bufferSize] ;
         ByteArrayOutputStream imageBuffer = new ByteArrayOutputStream(1024*50);
         httpInput = new DataInputStream( httpCon.openInputStream() );
                   System.out.println("Http-Input Connecting Establish Successfully");
                   httpOutput = new DataOutputStream( httpCon.openOutputStream() );
                   System.out.println("Http-Output Establish Successfully");
    int size = 0 ;
    // read all image data ....
         while ( ( size = httpInput.read( byteInput , 0 , bufferSize ) ) != -1 )
                        imageBuffer.write( byteInput , 0 , size ) ;
    // get byte from buffer stream
              byte byteImage[] = imageBuffer.toByteArray();
                   System.out.println("read byte " + byteImage.length );
         // convert byte to image ...
         image = Image.createImage( byteImage , 0 , byteImage.length );
         return image ;
         //return null ;
    catch( IOException e )
                   System.out.println("\nUnable to Perform Image IO Operation with Host");
         return null ;
    ....................................

  • I have made a webpage in HTML with several links to JPGs / GIFs. The text matter opens perfectly but not the images. Please help me

    I have made a web page in HTML with several links to JPGs / GIFs. While text matter opens up perfectly, but not the images. Please help me.
    == This happened ==
    Every time Firefox opened
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; CTS Version; .NET CLR 1.1.4322; .NET CLR 2.0.50727)

    URL of that web page?

  • Load, crop and saving jpg and gif images with JFileChooser

    Hello!
    I wonder is there someone out there who can help me with a applic that load, (crop) and saving images using JFileChooser with a simple GUI as possible. I'm new to programming and i hope someone can show me.
    Tor

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    public class ChopShop extends JPanel {
        JFileChooser fileChooser;
        BufferedImage image;
        Rectangle clip = new Rectangle(50,50,150,150);
        boolean showClip = true;
        public ChopShop() {
            fileChooser = new JFileChooser(".");
            fileChooser.setFileFilter(new ImageFilter());
        public void setClip(int x, int y) {
            clip.setLocation(x, y);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(image != null) {
                int x = (getWidth() - image.getWidth())/2;
                int y = (getHeight() - image.getHeight())/2;
                g2.drawImage(image, x, y, this);
            if(showClip) {
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize() {
            int width = 400;
            int height = 400;
            int margin = 20;
            if(image != null) {
                width = image.getWidth() + 2*margin;
                height = image.getHeight() + 2*margin;
            return new Dimension(width, height);
        private void showOpenDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    image = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("Read error for " + file.getPath() +
                                       ": " + e.getMessage());
                    image = null;
                revalidate();
                repaint();
        private void showSaveDialog() {
            if(image == null || !showClip)
                return;
            if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                String ext = ((ImageFilter)fileChooser.getFileFilter()).getExtension(file);
                // Make sure we have an ImageWriter for this extension.
                if(!canWriteTo(ext)) {
                    System.out.println("Cannot write image to " + ext + " file.");
                    String[] formatNames = ImageIO.getWriterFormatNames();
                    System.out.println("Supported extensions are:");
                    for(int j = 0; j < formatNames.length; j++)
                        System.out.println(formatNames[j]);
                    return;
                // If file exists, warn user, confirm overwrite.
                if(file.exists()) {
                    String message = "<html>" + file.getPath() + " already exists" +
                                     "<br>Do you want to replace it?";
                    int n = JOptionPane.showConfirmDialog(this, message, "Confirm",
                                                          JOptionPane.YES_NO_OPTION);
                    if(n != JOptionPane.YES_OPTION)
                        return;
                // Get the clipped image, if available. This is a subImage
                // of image -> they share the same data. Handle with care.
                BufferedImage clipped = getClippedImage();
                if(clipped == null)
                    return;
                // Copy the clipped image for safety.
                BufferedImage cropped = copy(clipped);
                boolean success = false;
                // Write cropped to the user-selected file.
                try {
                    success = ImageIO.write(cropped, ext, file);
                } catch(IOException e) {
                    System.out.println("Write error for " + file.getPath() +
                                       ": " + e.getMessage());
                System.out.println("writing image to " + file.getPath() +
                                   " was" + (success ? "" : " not") + " successful");
        private boolean canWriteTo(String ext) {
            // Support for writing gif format is new in j2se 1.6
            String[] formatNames = ImageIO.getWriterFormatNames();
            //System.out.printf("writer formats = %s%n",
            //                   java.util.Arrays.toString(formatNames));
            for(int j = 0; j < formatNames.length; j++) {
                if(formatNames[j].equalsIgnoreCase(ext))
                    return true;
            return false;
        private BufferedImage getClippedImage() {
            int w = getWidth();
            int h = getHeight();
            int iw = image.getWidth();
            int ih = image.getHeight();
            // Find origin of centered image.
            int ix = (w - iw)/2;
            int iy = (h - ih)/2;
            // Find clip location relative to image origin.
            int x = clip.x - ix;
            int y = clip.y - iy;
            // clip must be within image bounds to continue.
            if(x < 0 || x + clip.width  > iw || y < 0 || y + clip.height > ih) {
                System.out.println("clip is outside image boundries");
                return null;
            BufferedImage subImage = null;
            try {
                subImage = image.getSubimage(x, y, clip.width, clip.height);
            } catch(RasterFormatException e) {
                System.out.println("RFE: " + e.getMessage());
            // Caution: subImage is not independent from image. Changes
            // to one will affect the other. Copying is recommended.
            return subImage;
        private BufferedImage copy(BufferedImage src) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dest = new BufferedImage(w, h, src.getType());
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(src, 0, 0, this);
            g2.dispose();
            return dest;
        private JPanel getControls() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(getCropPanel(), gbc);
            panel.add(getImagePanel(), gbc);
            return panel;
        private JPanel getCropPanel() {
            JToggleButton toggle = new JToggleButton("clip", showClip);
            toggle.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showClip = ((AbstractButton)e.getSource()).isSelected();
                    repaint();
            SpinnerNumberModel widthModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner widthSpinner = new JSpinner(widthModel);
            SpinnerNumberModel heightModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner heightSpinner = new JSpinner(heightModel);
            ChangeListener cl = new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    JSpinner spinner = (JSpinner)e.getSource();
                    int value = ((Number)spinner.getValue()).intValue();
                    if(spinner == widthSpinner)
                        clip.width = value;
                    if(spinner == heightSpinner)
                        clip.height = value;
                    repaint();
            widthSpinner.addChangeListener(cl);
            heightSpinner.addChangeListener(cl);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            panel.add(toggle, gbc);
            addComponents(new JLabel("width"),  widthSpinner,  panel, gbc);
            addComponents(new JLabel("height"), heightSpinner, panel, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc) {
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        private JPanel getImagePanel() {
            final JButton open = new JButton("open");
            final JButton save = new JButton("save");
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JButton button = (JButton)e.getSource();
                    if(button == open)
                        showOpenDialog();
                    if(button == save)
                        showSaveDialog();
            open.addActionListener(al);
            save.addActionListener(al);
            JPanel panel = new JPanel();
            panel.add(open);
            panel.add(save);
            return panel;
        public static void main(String[] args) {
            ChopShop chopShop = new ChopShop();
            ClipMover mover = new ClipMover(chopShop);
            chopShop.addMouseListener(mover);
            chopShop.addMouseMotionListener(mover);
            JFrame f = new JFrame("click inside rectangle to drag");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(chopShop));
            f.getContentPane().add(chopShop.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    class ImageFilter extends FileFilter {
        static String GIF = "gif";
        static String JPG = "jpg";
        static String PNG = "png";
        // bmp okay in j2se 1.5+
        public boolean accept(File file) {
            if(file.isDirectory())
                return true;
            String ext = getExtension(file).toLowerCase();
            if(ext.equals(GIF) || ext.equals(JPG) || ext.equals(PNG))
                return true;
            return false;
        public String getDescription() {
            return "gif, jpg, png images";
        public String getExtension(File file) {
            String s = file.getPath();
            int dot = s.lastIndexOf(".");
            return (dot != -1) ? s.substring(dot+1) : "";
    class ClipMover extends MouseInputAdapter {
        ChopShop component;
        Point offset = new Point();
        boolean dragging = false;
        public ClipMover(ChopShop cs) {
            component = cs;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(component.clip.contains(p)) {
                offset.x = p.x - component.clip.x;
                offset.y = p.y - component.clip.y;
                dragging = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                component.setClip(x, y);
    }

  • How to display  servlet dynamically generated image ?

    Hi,
    How to display servlet dynamically generated image ?
    I have a servlet generating a buffered image in the doGet. I want to display the image in a jsp page with other information. I'm not able to get it properly displayed.
    **Try n# 1 **************************************************************
    This displays my image but nothing elle :
    ServletOutputStream sos = pResponse.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(img);
    **Try n# 2 ****************************************************************
    I tried also :
    In the servlet :
         request.setAttribute("renderedImage", img);
    and in the jsp page :
         BufferedImage image = (BufferedImage) request.getAttribute("renderedImage");
         <img src="<%=ImageIO.write(image,"jpeg",response.getOutputStream())%>" width="300" height="280"/>
    This last try draws big crap in the jsp page, thank you in advance.
    Nelson

    Call another servlet from the IMG tag. Have the servlet stream out the image using ImageIO (instead of writing HTML).

Maybe you are looking for

  • Iphone 5s ios7.1

    My voice command and voice to text isnt picking up anything since I switched to ios 7.1 Is there any way to go back to ios7 I just downloaded it yesterday.

  • Sleep button no longer works

    Sleep button no longer works, how do I get it fixed and how much will it cost. It is a repalcement from Sprint insurance and only hac it about 5 months.

  • Persistent HTTP Requests in BSP: Can you Flush the Response without Ending It?

    Hello all, I have been looking for a way to implement a persistent HTTP Request in a BSP.  This means the server keeps the request open as long as possible and sends data periodically to the browser without closing the request.  In other development

  • Append text in JTextArea

    greetings.. i'm having the following code: public class GUI extends JPanel implements ActionListener   JTextArea theText;   public GUI()      // and so on and so forth that initializes the textarea       displayToTextArea("call from inside"); public

  • Photoshop 9 and windows 8

    i installed photoshop elements 9 in windows 8 64 bit the organizer will open but the edit will not respond  does anyony have a solution ??