Code:
   1.
      import java.awt.Container;
   2.
      import java.awt.FlowLayout;
   3.
      import java.awt.Font;
   4.
      import java.awt.FontMetrics;
   5.
      import java.awt.Graphics;
   6.
      import java.awt.Graphics2D;
   7.
      import java.awt.Image;
   8.
      import java.awt.RenderingHints;
   9.
      import java.awt.event.ActionEvent;
  10.
      import java.awt.event.ActionListener;
  11.
      import java.awt.image.BufferedImage;
  12.
      import java.awt.image.RescaleOp;
  13.
      import java.io.BufferedReader;
  14.
      import java.io.ByteArrayOutputStream;
  15.
      import java.io.DataOutputStream;
  16.
      import java.io.File;
  17.
      import java.io.IOException;
  18.
      import java.io.InputStreamReader;
  19.
      import java.net.HttpURLConnection;
  20.
      import java.net.URL;
  21.
      import java.util.StringTokenizer;
  22.
      import javax.imageio.ImageIO;
  23.
      import javax.imageio.ImageWriteParam;
  24.
      import javax.imageio.ImageWriter;
  25.
      import javax.imageio.stream.ImageOutputStream;
  26.
      import javax.imageio.stream.MemoryCacheImageOutputStream;
  27.
      import javax.swing.JApplet;
  28.
      import javax.swing.JButton;
  29.
      import javax.swing.JOptionPane;
  30.
      import javax.swing.JTextArea;
  31.
      import javax.swing.JTextField;
  32.
       
  33.
      @SuppressWarnings("serial")
  34.
      public class AppletEE extends JApplet {
  35.
      private JTextField tf = new JTextField("", 15);
  36.
      private JTextArea ta = new JTextArea( "",8,40);
  37.
      private JButton button1 = new JButton("Preview");
  38.
      private JButton button2 = new JButton("Generate Image");
  39.
      Font font1;
  40.
      Font font2;
  41.
      BufferedImage bgImage;
  42.
      BufferedImage fgImage;
  43.
      BufferedImage overlayedImage;
  44.
      final int xc=170;
  45.
      public void init() {
  46.
      this.setSize(450, 550);
  47.
      Container cp = getContentPane();
  48.
      font1= new Font("Arial", Font.PLAIN, 50);
  49.
      font2= new Font("Arial", Font.PLAIN, 30);
  50.
      cp.setLayout(new FlowLayout());
  51.
      cp.add(tf);
  52.
      cp.add(ta);
  53.
      cp.add(button1);
  54.
      cp.add(button2);
  55.
      button1.addActionListener(new ActionListener() {
  56.
      public void actionPerformed(ActionEvent e) {
  57.
      try {
  58.
      // Read from a URL
  59.
      URL url = new URL("http://192.168.1.2/bg.png");
  60.
      bgImage = imageToBufferedImage(ImageIO.read(url));
  61.
      } catch (IOException e1) {
  62.
      System.out.println("url error");
  63.
      }
  64.
      overlayedImage=bgImage;
  65.
      generate();
  66.
      repaint();
  67.
      }
  68.
      });
  69.
      button2.addActionListener(new ActionListener() {
  70.
      public void actionPerformed(ActionEvent e) {
  71.
      try {
  72.
      // Read from a URL
  73.
      URL url = new URL("http://192.168.1.2/bg.png");
  74.
      bgImage = imageToBufferedImage(ImageIO.read(url));
  75.
      } catch (IOException e1) {
  76.
      System.out.println("url error");
  77.
      }
  78.
      overlayedImage=bgImage;
  79.
      generate();
  80.
      save();
  81.
      tf.setText("");
  82.
      ta.setText("");
  83.
      }
  84.
      });
  85.
      }
  86.
      public void paint(Graphics g){
  87.
      g.drawImage(overlayedImage,0,200,450,337,this);
  88.
       
  89.
      }
  90.
      public void generate(){
  91.
       
  92.
      if(tf.getText().length()==0){
  93.
      tf.setText(" ");
  94.
      }
  95.
      FontMetrics fm = this.getFontMetrics(font1);
  96.
      BufferedImage imageA = new BufferedImage(fm.stringWidth(tf.getText()), (int) (fm.getHeight()*1.5), BufferedImage.OPAQUE);
  97.
      Graphics2D g = imageA.createGraphics();
  98.
      g.setFont(font1);
  99.
      g.drawString(tf.getText(), 0, fm.getHeight());
 100.
      g.dispose();
 101.
      RescaleOp op=new RescaleOp(-1.0f, 255f,null);
 102.
      imageA=op.filter(imageA, null);
 103.
      int lines=ta.getLineCount();
 104.
      if(lines>8){
 105.
      lines=8;
 106.
      }
 107.
      int z=(int) ((bgImage.getHeight()-(font1.getSize()*1.5+font2.getSize()*1.5*lines))/2-font2.getSize());
 108.
      overlayedImage=overlayImages(bgImage, imageA, ((bgImage.getWidth())/2-(imageA.getWidth())/2), z);
 109.
      int enter=0;
 110.
      char[] temp0=new char[ta.getText().length()];
 111.
      ta.getText().getChars(0, ta.getText().length(), temp0, 0);
 112.
      if(ta.getText().length()>4){
 113.
      for(int t=0; t<ta.getText().length()-1; t++){
 114.
      if(temp0[t]=='\n'&&temp0[t+1]=='\n'){
 115.
      enter++;
 116.
      }
 117.
      }
 118.
      if(enter!=0){
 119.
      temp0=new char[ta.getText().length()+enter];
 120.
      ta.getText().getChars(0, ta.getText().length(), temp0, 0);
 121.
      for(int t=0; t<ta.getText().length()-1; t++){
 122.
      if(temp0[t]=='\n'&&temp0[t+1]=='\n'){
 123.
      for(int u=temp0.length-1; u>t; u--){
 124.
      temp0[u]=temp0[u-1];
 125.
      }
 126.
      temp0[t+1]=' ';
 127.
      }
 128.
      }
 129.
      }
 130.
      }
 131.
      String s[] = new String[10];
 132.
      StringTokenizer st=new StringTokenizer(new String(temp0),"\n");
 133.
      int r=0;
 134.
      boolean done=false;
 135.
      while(st.hasMoreTokens()&&done==false){
 136.
      s[r]=st.nextToken();
 137.
      while(s[r].length()>47&&done==false){
 138.
      char[] temp1=new char[s[r].length()-47];
 139.
      char[] temp2=new char[47];
 140.
      s[r].getChars(47, s[r].length(), temp1, 0);
 141.
      s[r].getChars(0, 47, temp2, 0);
 142.
      s[r]=new String(temp2);
 143.
      s[r+1]=new String(temp1);
 144.
      r++;
 145.
      if(r>=8){
 146.
      done=true;
 147.
      }
 148.
      }
 149.
      r++;
 150.
      System.out.print(r);
 151.
      if(r>=8){
 152.
      done=true;
 153.
      }
 154.
      }
 155.
      fm = this.getFontMetrics(font2);
 156.
      BufferedImage textImage;
 157.
      for(int v=0; v<r; v++){
 158.
      textImage = new BufferedImage(fm.stringWidth(ta.getText()), (int) (fm.getHeight()*1.5), BufferedImage.OPAQUE);
 159.
      g = textImage.createGraphics();
 160.
      g.setFont(font2);
 161.
      g.drawString(s[v], 0, fm.getHeight());
 162.
      g.dispose();
 163.
      z=(int) ((bgImage.getHeight()-(font1.getSize()*1.5+font2.getSize()*1.5*lines))/2+font1.getSize()*1.5+font2.getSize()*1.5*v);
 164.
      textImage=op.filter(textImage, null);
 165.
      overlayedImage=overlayImages(overlayedImage, textImage, xc, z);
 166.
      }
 167.
      }
 168.
      public static BufferedImage imageToBufferedImage(Image im) {
 169.
      BufferedImage bi = new BufferedImage(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
 170.
      Graphics bg = bi.getGraphics();
 171.
      bg.drawImage(im, 0, 0, null);
 172.
      bg.dispose();
 173.
      return bi;
 174.
      }
 175.
      public void save(){
 176.
      if(overlayedImage!=null){
 177.
      int v=0;
 178.
      boolean found=false;
 179.
      while(found==false){
 180.
      try{
 181.
      URL url = new URL("http://192.168.1.2/text" + v + ".png");
 182.
      ImageIO.read(url);
 183.
      //ImageIO.read(new File(saveFilePath + "text" + v + ".png"));
 184.
      v++;
 185.
      }catch(Exception e){
 186.
      found=true;
 187.
      }
 188.
      }
 189.
      String s=writeImage(overlayedImage, "http://192.168.1.2/text" + v + ".png", "png");
 190.
      ta.setText(s);
 191.
      overlayedImage.flush();
 192.
      }else
 193.
      System.out.print("Problem with overlay...");
 194.
      }
 195.
      public static BufferedImage overlayImages(BufferedImage bgImage, BufferedImage fgImage, int mr, int nr ){//lägger en bild på en annan
 196.
      if(fgImage.getHeight()>bgImage.getHeight()||fgImage.getWidth()>fgImage.getWidth()){
 197.
      JOptionPane.showMessageDialog(null, "Use smaller text size");
 198.
      return null;
 199.
      }
 200.
      Graphics2D g=bgImage.createGraphics();
 201.
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 202.
      g.drawImage(bgImage, 0, 0, null);
 203.
      g.drawImage(fgImage, mr, nr, null);
 204.
      g.dispose();
 205.
      return bgImage;
 206.
      }
 207.
      public static BufferedImage readImage(String filelocation){
 208.
      BufferedImage img=null;
 209.
      try{
 210.
      img=ImageIO.read(new File(filelocation));
 211.
      }catch(IOException e){
 212.
      e.printStackTrace();
 213.
      }
 214.
      return img;
 215.
      }
 216.
      public static String writeImage(BufferedImage img, String filelocation, String extension){
 217.
      DataUpload du = new DataUpload();
 218.
      boolean bo = du.UploadImage(filelocation, img);
 219.
      int rc = du.GetResponseCode();
 220.
      String feedback = du.GetServerFeedback();
 221.
      return (""+bo+rc+feedback);
 222.
      }
 223.
      }
 224.
       
 225.
      class DataUpload{
 226.
      /** The field name as expected by the PHP script, equivalent to the name in the tag input type="file"
 227.
      * in an HTML upload form.
 228.
      */
 229.
      private static final String FIELD_NAME = "image";
 230.
      /** PHP script name. */
 231.
      // I hard-code it here, I suppose there is no need for several scripts per applet...
 232.
      private static final String SCRIPT_NAME = "Upload.php";
 233.
      /** URL path to the PHP script. */
 234.
      private static final String BASE_URL = "http://192.168.1.2/EE";
 235.
      private String boundary;
 236.
      private String uploadURL;
 237.
      /** The connection to the server. */
 238.
      private HttpURLConnection connection;
 239.
      /** The output stream to write the binary data. */
 240.
      private DataOutputStream output;
 241.
       
 242.
      DataUpload(){
 243.
      // Mime boundary of the various parts of the message.
 244.
      boundary = "-----DataUploadClass-----PhiLhoSoft-----" + System.currentTimeMillis();
 245.
      // We can add a optional parameters, eg. a string given by the user, parameters used, etc.
 246.
      uploadURL = BASE_URL + "/" + SCRIPT_NAME;// + "?optionalParam=value&foo=bar";
 247.
      }
 248.
       
 249.
      /** Pushes image to server. */
 250.
      boolean UploadImage(String fileName, BufferedImage image)
 251.
      {
 252.
      String imageType = null, imageMimeType = null;
 253.
      boolean bUseOtherMethod = false;
 254.
      if (fileName.endsWith("png"))
 255.
      {
 256.
      imageType = "png";
 257.
      imageMimeType = "image/png";
 258.
      }
 259.
      else if (fileName.endsWith("jpg"))
 260.
      {
 261.
      imageType = "jpg";
 262.
      imageMimeType = "image/jpeg";
 263.
      }
 264.
      else if (fileName.endsWith("jpeg"))
 265.
      {
 266.
      imageType = "jpeg";
 267.
      imageMimeType = "image/jpeg";
 268.
      bUseOtherMethod = true;
 269.
      }
 270.
      else
 271.
      {
 272.
      return false; // Unsupported image format
 273.
      }
 274.
       
 275.
      try
 276.
      {
 277.
      boolean isOK = StartPOSTRequest(fileName, imageMimeType);
 278.
      if (!isOK)
 279.
      return false;
 280.
       
 281.
      // Output the encoded image data
 282.
      if (!bUseOtherMethod)
 283.
      {
 284.
      // Uses the default method
 285.
      ImageIO.write(image, imageType, output);
 286.
      }
 287.
      else
 288.
      {
 289.
      // Alternative for better Jpeg quality control
 290.
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
 291.
       
 292.
      java.util.Iterator iter = ImageIO.getImageWritersByFormatName(imageType);
 293.
      if (iter.hasNext())
 294.
      {
 295.
      ImageWriter writer = (ImageWriter) iter.next();
 296.
      ImageWriteParam iwp = writer.getDefaultWriteParam();
 297.
      iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
 298.
      iwp.setCompressionQuality(1.0f);
 299.
       
 300.
      ImageOutputStream ios = new MemoryCacheImageOutputStream(baos);
 301.
      writer.setOutput(ios);
 302.
      writer.write(image);
 303.
      byte[] b = baos.toByteArray();
 304.
      output.write(b, 0, b.length);
 305.
      }
 306.
      }
 307.
       
 308.
      // And actually do the send (flush output and close it)
 309.
      EndPOSTRequest();
 310.
      }
 311.
      catch (Exception e)
 312.
      {
 313.
      e.printStackTrace();
 314.
      return false; // Problem
 315.
      }
 316.
      finally
 317.
      {
 318.
      if (output != null)
 319.
      {
 320.
      try { output.close(); } catch (IOException ioe) {}
 321.
      }
 322.
      }
 323.
       
 324.
      return true; // OK
 325.
      }
 326.
       
 327.
      /** Reads output from server. */
 328.
      String GetServerFeedback()
 329.
      {
 330.
      if (connection == null)
 331.
      {
 332.
      // ERROR: Can't get server feedback without first uploading data!
 333.
      return null;
 334.
      }
 335.
      BufferedReader input = null;
 336.
      StringBuffer answer = new StringBuffer();
 337.
      try
 338.
      {
 339.
      input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 340.
      String answerLine = null;
 341.
      do
 342.
      {
 343.
      answerLine = input.readLine();
 344.
      if (answerLine != null)
 345.
      {
 346.
      answer.append(answerLine + "\n");
 347.
      }
 348.
      } while (answerLine != null);
 349.
      }
 350.
      catch (Exception e)
 351.
      {
 352.
      // Can display some feedback to user there, or just ignore the issue
 353.
      e.printStackTrace();
 354.
      return null; // Problem
 355.
      }
 356.
      finally
 357.
      {
 358.
      if (input != null)
 359.
      {
 360.
      try { input.close(); } catch (IOException ioe) {}
 361.
      }
 362.
      }
 363.
       
 364.
      return answer.toString();
 365.
      }
 366.
       
 367.
      int GetResponseCode()
 368.
      {
 369.
      int responseCode = -1;
 370.
      if (connection == null)
 371.
      {
 372.
      // ERROR: Can't get server response without first uploading data!
 373.
      return -1;
 374.
      }
 375.
      // Note that 200 means OK
 376.
      try
 377.
      {
 378.
      responseCode = connection.getResponseCode();
 379.
      }
 380.
      catch (IOException ioe)
 381.
      {
 382.
      }
 383.
      return responseCode;
 384.
      }
 385.
       
 386.
      /*-- Private section --*/
 387.
       
 388.
      private boolean StartPOSTRequest(String fileName, String dataMimeType)
 389.
      {
 390.
      try
 391.
      {
 392.
      URL url = new URL(uploadURL); // throws MalformedURLException
 393.
      connection = (HttpURLConnection) url.openConnection(); // throws IOException
 394.
      // connection is probably of HttpURLConnection type now
 395.
       
 396.
      connection.setDoOutput(true); // We output stuff
 397.
      connection.setRequestMethod("POST"); // With POST method
 398.
      connection.setDoInput(true); // We want feedback!
 399.
      connection.setUseCaches(false); // No cache, it is (supposed to be) a new image each time, even if URL is always the same
 400.
       
 401.
      // Post multipart data
 402.
      // Set request headers
 403.
      // Might put something like "Content-Length: 8266"
 404.
      connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
 405.
      // throws IllegalStateException, NullPointerException
 406.
       
 407.
      // Open a stream which can write to the URL
 408.
      output = new DataOutputStream(connection.getOutputStream());
 409.
      // the get throws IOException, UnknownServiceException
 410.
       
 411.
      // Write content to the server, begin with the tag that says a content element is coming
 412.
      output.writeBytes("--" + boundary + "\r\n"); // throws IOException
 413.
       
 414.
      // Describe the content:
 415.
      // filename isn't really important here, it is probably ignored by the upload script, or can be set to user name if logged in
 416.
      output.writeBytes("Content-Disposition: form-data; name=\"" + FIELD_NAME +
 417.
      "\"; filename=\"" + fileName + "\"\r\n");
 418.
      // Mime type of the data, like image/jpeg or image/png
 419.
      // Likely to be ignored by the PHP script (which can't trust such external info) but (might be) mandatory and nice to indicate anyway
 420.
      output.writeBytes("Content-Type: " + dataMimeType + "\r\n");
 421.
      // By default it is Base64 encoding (that's what most browsers use), but here we don't use this,
 422.
      // for simplicity sake and because it is less data to transmit. As long as destination server understands it...
 423.
      // See http://www.freesoft.org/CIE/RFC/1521/5.htm for details
 424.
      output.writeBytes("Content-Transfer-Encoding: binary\r\n\r\n");
 425.
      }
 426.
      catch (Exception e) // Indistinctly catch all kinds of exceptions this code can throw at us
 427.
      {
 428.
      // Can display some feedback to user there, or just ignore the issue
 429.
      e.printStackTrace();
 430.
      return false; // Problem
 431.
      }
 432.
       
 433.
      return true;
 434.
      }
 435.
      private boolean EndPOSTRequest()
 436.
      {
 437.
      try
 438.
      {
 439.
      // Close the multipart form request
 440.
      output.writeBytes("\r\n--" + boundary + "--\r\n\r\n");
 441.
       
 442.
      // And actually do the send (flush output and close it)
 443.
      output.flush(); // throws IOException
 444.
      }
 445.
      catch (Exception e) // Indistinctly catch all kinds of exceptions this code can throw at us
 446.
      {
 447.
      // Can display some feedback to user there, or just ignore the issue
 448.
      e.printStackTrace();
 449.
      return false; // Problem
 450.
      }
 451.
       
 452.
      return true;
 453.
      }
 454.
      }


Sponsored Links