Rezigian
Rezigian

Reputation: 11

Saving an applet as an image

So I am not very experienced when it comes to applets, but I have an applet that draws something based on user input, what is the easiest way to save what the applet creates as an image file? (preferably after the user clicks "applet" then like "save image")

Upvotes: 1

Views: 93

Answers (2)

Invictus
Invictus

Reputation: 181

I'm pretty sure this isn't supported in the Java libraries. Most likely what you would have to do is to make an image file yourself - let's say a bitmap for simplicity's sake - and iterate over the pixels and set them yourself based on your image data, more or less making your own rendering engine.

To clarify, that would mean that you'd have to save the user's input, and use that to build the image file, as well as the image on-screen.

Here's a pseudo-code example of what I mean:

ArrayList rules;  //records the user's inputs used to make the image  
                  //e.g. "red line from pixel (3,5) -> (5,8)"
Image savedImage; //open an image file - make sure to set its dimensions to the
                  //dimensions of the image on-screen
for (x = 0 -> savedImage.width)
{
  for (y = 0 -> savedImage.height)
  {
    for (r = 0 -> rules.size())
    {
      if (rules.get(r).affects(x,y)) //checking to see if this input
      {                              //affected this pixel
        savedImage.pixelAt(x,y).apply(rules.get(r)); //if so, apply the rule's
                                                     //effect to this pixel
      }
    }
  }
}

I'm pretty sure that the Rules class and the Image class you'd have to make yourself, but they shouldn't be too difficult to make.

Though I would like to point out that I am assuming that you wish to do this programmatically, such that the image is either saved automatically when the user is done or when the user tells the applet to save it.

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168845

I have an applet that draws something based on user input,

Have the applet instead use an existing <img ..> element on the page. Whenever the image changes, encode the image as Base-64 and write it to the img.src attribute.

The applet would need to manipulate the Document Object Model of the web page that hosts it, using the Java/JavaScript bridge available to applets.

..what is the easiest way to save what the applet creates as an image file? (preferably after the user clicks "applet" then like "save image")

That ability should be provided automatically by the browser if it supports saving base 64 encoded images.


Of course, if deploying the applet using Java Web Start, it is possible to use the FileSaveService of the JNLP API.

Upvotes: 1

Related Questions