Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

Thursday, July 12, 2018

Java > Convert text content to Image > Using Java Create An Image And Save To File With Transparent Background

For example, from the string Pritom K Mondal, I would like to generate this simple image:
package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class TextToImage {
    public static void main(String[] args) {
        String text = "Pritom K Mondal";

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        Font font = new Font("Arial", Font.PLAIN, 48);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(text) + 20;
        int height = fm.getHeight();
        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        g2d.drawString(text, 10, fm.getAscent());
        g2d.dispose();
        try {
            ImageIO.write(img, "png", new File("Image.png"));
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
And output is like below:


Saturday, May 16, 2015

Java Create Watermark Text Or Fill Area To An Image


package com.pkm;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class WatermarkTextToImage {
    public static void main(String[] args) throws Exception {
 ImageIcon photo = new ImageIcon("100_6929.jpg");
 BufferedImage bufferedImage = new BufferedImage(photo.getIconWidth(),
  photo.getIconHeight(),
  BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

        g2d.drawImage(photo.getImage(), 0, 0, null);

        AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
        g2d.setComposite(alpha);

        g2d.setColor(Color.white);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
         RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        g2d.setFont(new Font("Arial", Font.BOLD, 100));

        String watermark = "Pritom Kumar Mondal";

        FontMetrics fontMetrics = g2d.getFontMetrics();
        Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

        g2d.drawString(watermark,
         (photo.getIconWidth() - (int) rect.getWidth()) / 2,
         (photo.getIconHeight() - (int) rect.getHeight()) / 2);

        alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f);
        g2d.setComposite(alpha);
        g2d.setColor(Color.red);
        g2d.fillOval(0, 0, photo.getIconWidth(), photo.getIconHeight());

        //Free graphic resources
        ImageIO.write(bufferedImage, "JPEG", new File("100_6929_Watermark.JPG"));
        g2d.dispose();
    }
}

Input & Output Image Respectively

Friday, May 15, 2015

Using Java Create An Image And Save To File

package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Main {
    public static void main(String args[]) throws Exception {
 try {
     int width = 200, height = 200;
     // TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
     // into integer pixels
     BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
     Graphics2D ig2 = bi.createGraphics();
  
     ig2.setColor(Color.red);
     ig2.fillRect(0, 0, width, height);
  
     ig2.setColor(Color.green);
     ig2.fillOval(0, 0, width, height);
 
     Font font = new Font("TimesRoman", Font.BOLD, 80);
     ig2.setFont(font);
     String message = "PKM";
     FontMetrics fontMetrics = ig2.getFontMetrics();
     int stringWidth = fontMetrics.stringWidth(message);
     int stringHeight = fontMetrics.getAscent();
     ig2.setPaint(Color.black);
   
     ig2.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4); 
   
     ImageIO.write(bi, "PNG", new File("ImageName.PNG"));   
     ImageIO.write(bi, "JPEG", new File("ImageName.JPG"));   
     ImageIO.write(bi, "gif", new File("ImageName.GIF"));   
     System.out.println("Image Create Done");  
 }  
 catch (Exception ex) {  
     ex.printStackTrace();  
 } 
    }
}

Output


Friday, September 6, 2013

PHP image output and browser caching

The code is pretty simple, and borrows heavily from code pasted by mandor at mandor dot net for the PHP header function. We generalised it for different graphic file types and a second function so it works when PHP is an Apache module or cgi.
The first function displayGraphicFile is to return a graphic file. The function does assume the file exists.
// Return the requested graphic file to the browser
// or a 304 code to use the cached browser copy
function displayGraphicFile ($graphicFileName, $fileType='jpeg') {
  $fileModTime = filemtime($graphicFileName);
  // Getting headers sent by the client.
  $headers = getRequestHeaders();
  // Checking if the client is validating his cache and if it is current.
  if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $fileModTime)) {

    // Client's cache IS current, so we just respond '304 Not Modified'.
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).' GMT', true, 304);
  } else {
    // Image not cached or cache outdated, we respond '200 OK' and output the image.
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).' GMT', true, 200);
    header('Content-type: image/'.$fileType);
    header('Content-transfer-encoding: binary');
    header('Content-length: '.filesize($graphicFileName));
    readfile($graphicFileName);
  }
}
The second function to get the header request details. We specifically require the ‘If-Modified-Since’ header.
// return the browser request header
// use built in apache ftn when PHP built as module,
// or query $_SERVER when cgi
function getRequestHeaders() {
  if (function_exists("apache_request_headers")) {
    if($headers = apache_request_headers()) {
      return $headers;

    }
  }
  $headers = array();
  // Grab the IF_MODIFIED_SINCE header
  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  }
  return $headers;
}

Sunday, August 4, 2013

Image Data URIs with JavaScript

<img src="your_image.png" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>


You will need to create a canvas element with the correct dimensions and copy the image data with thedrawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.
It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL();

    return dataURL;
}
var myImage = document.getElementById('myimage');
var imageData = getbase64Image(myImage);
Return like something: "data:image/png;base64,BASE_64_IMAGE_DATA"; 

Image Data URIs with PHP

If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves a network request for each image, and if you're the paranoid type, can prevent exposure of directory paths. Since creating data URIs is incredibly easy, let me show you how to do it with PHP.

The PHP

Start by reading in the image using file_get_contents (or any other PHP method you'd like), then convert the image to base64 using base64_encode:
// A few settings
$image = 'cricci.jpg';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="',$src,'">';
With the image data in base64 format, the last step is placing that data within the data URI format, including the image's MIME type. This would make for a good function:
function getDataURI($image, $mime = '') {
	return 'data: '.(function_exists('mime_content_type') ? mime_content_type($image) : $mime).';base64,'.base64_encode(file_get_contents($image));
}
The thing to remember is that IE7 and lower don't support data URIs, so keep that in mind if you're considering switching from image paths to data URIs!

http://davidwalsh.name/data-uri-php 

Thursday, June 27, 2013

jQuery/Javascript to replace broken images

Handle the onError event for the image to reassign its source using JavaScript:
function(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>
Or without a JavaScript function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />