public static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight) {
BufferedImage scaledImage = null;
if (imageToScale != null) {
scaledImage = new BufferedImage(dWidth, dHeight, imageToScale.getType());
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.drawImage(imageToScale, 0, 0, dWidth, dHeight, null);
graphics2D.dispose();
}
return scaledImage;
}
@Override
public void save(String token, MultipartFile multipartFile) throws Exception {
AvatarStoreRequest request = decodeToken(token);
if (LocalDateTime.now().isAfter(request.getExpires())) {
throw new BadRequestException("Token is expired!");
}
save(request, multipartFile.getInputStream(), multipartFile.getSize());
}
@Override //初始随机生成图片图片
public void init(AvatarStoreRequest request) throws Exception {
BufferedImage identicon = IdenticonGenerator.generateIdenticons(Objects.requireNonNull(md5Hex(request.getAvatarType().toString() + request.getEntityIdentifier().toLowerCase())), 128, 128);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(identicon, "png", byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
save(request, inputStream, byteArrayOutputStream.size());
}
//生成三张不同像素的图片
private void save(AvatarStoreRequest request, InputStream imageInputStream, long imageSize) throws Exception {
if (imageSize > imageConfig.getMaxAvatarUploadingFileSize()) {
throw new BadRequestException("Uploaded file is too big!");
}
Path dirPath = getImageDir(request.getAvatarType(), request.getEntityId());
if (!Files.exists(dirPath)) {
Files.createDirectories(dirPath);
}
BufferedImage image = ImageIO.read(imageInputStream);
// TODO: make sure the content type: multipartFile.getContentType()
for (AvatarStoreRequest.Size size : imageConfig.getAvatarSizes()) {
final String formatName = "png";
Path filePath = getImagePath(request.getAvatarType(), request.getEntityId(), size, formatName);
File outputFile = new File(filePath.toString());
Files.deleteIfExists(filePath);
if (image.getWidth() == size.getWidth() && image.getHeight() == size.getHeight()) {
ImageIO.write(image, formatName, outputFile);
} else {
BufferedImage resizedImage = scale(image, size.getWidth(), size.getHeight());
ImageIO.write(resizedImage, formatName, outputFile);
}
}
}
//随机生成一张图片
public static BufferedImage generateIdenticons(String text, int image_width, int image_height) {
int width = 5, height = 5;
byte[] hash = text.getBytes();
BufferedImage identicon = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = identicon.getRaster();
int[] background = new int[]{255, 255, 255, 0};
int[] foreground = new int[]{hash[0] & 255, hash[1] & 255, hash[2] & 255, 255};
for (int x = 0; x < width; x++) {
//Enforce horizontal symmetry
int i = x < 3 ? x : 4 - x;
for (int y = 0; y < height; y++) {
int[] pixelColor;
//toggle pixels based on bit being on/off
if ((hash[i] >> y & 1) == 1)
pixelColor = foreground;
else
pixelColor = background;
raster.setPixel(x, y, pixelColor);
}
}
BufferedImage finalImage = new BufferedImage(image_width, image_height, BufferedImage.TYPE_INT_ARGB);
//Scale image to the size you want
AffineTransform at = new AffineTransform();
at.scale(image_width / width, image_height / height);
AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
finalImage = op.filter(identicon, finalImage);
return finalImage;
}
public static String hex(byte[] array) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i]
& 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
}
public static String md5Hex(String message) {
try {
MessageDigest md =
MessageDigest.getInstance("MD5");
return hex(md.digest(message.getBytes("CP1252")));
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static void saveImage(BufferedImage bufferedImage, String name) {
File outputfile = new File(name + ".png");
try {
ImageIO.write(bufferedImage, "png", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}