Skip to content

Instantly share code, notes, and snippets.

@fairjm
Created November 7, 2017 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fairjm/2ac4c5f54158e30ce1afe09e171ace09 to your computer and use it in GitHub Desktop.
Save fairjm/2ac4c5f54158e30ce1afe09e171ace09 to your computer and use it in GitHub Desktop.
spring mvc imageIO add text to image
package com.cc.imageio.controller;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
*
* @author yuki
*
*/
@RestController
public class PicGenController {
private static File file = new File(PicGenController.class.getResource("/test.jpg").getFile());
private static Image image = null;
static {
try {
image = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
}
@GetMapping(value = "/genpic", produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] genPic(@RequestParam("text") String text) throws IOException {
int x = 200;
int y = 200;
int fontSize = 30;
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.setFont(new Font("隶书", Font.BOLD, fontSize));
g.setColor(Color.red);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
g.drawString(text, x, y);
g.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpeg", os);
// GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
// String[] fontFamilies = ge.getAvailableFontFamilyNames();
// for (String s : fontFamilies) {
// System.out.println(s);
// }
return os.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment