import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class AscPic {
public static void main(String[] args) throws IOException {
String path =
"d:/heart3.jpg"
;
String base =
"love"
;
BufferedImage image = ImageIO.read(
new
File(path));
float scale = (float) 1;
int width = (int) (image.getWidth()*scale)*3;
int height = (int) (image.getHeight()*scale);
Image img = image.getScaledInstance(width , height, Image.SCALE_DEFAULT);
image = toBufferedImage(img);
int[][] imageArray =
new
int[image.getHeight()][image.getWidth()];
int[] sum =
new
int[image.getWidth()];
int cnt = 0;
for
(int y = 0; y < image.getHeight(); y++) {
for
(int x = 0; x < image.getWidth(); x++) {
int color = image.getRGB(x, y);
int r=(color>>16)&0xff;
int g=(color>>8)&0xff;
int b=color&0xff;
float gray = 0.299f * r + 0.578f * g + 0.114f * b;
int index = Math.round(gray * (base.length()) / 255);
if
(index>=base.length()) {
imageArray[y][x] = -1;
}
else
{
imageArray[y][x] = cnt++;
sum[x]+=index;
}
}
}
for
(int i = 0;i<image.getHeight();i++){
for
(int j = 0;j<image.getWidth();j++){
if
(sum[j]==0)
continue
;
else
if
(imageArray[i][j]==-1)
System.out.print(
" "
);
else
System.out.print(base.charAt(imageArray[i][j]%base.length()));
}
System.out.println();
}
}
public static BufferedImage toBufferedImage(Image image) {
if
(image
instanceof
BufferedImage) {
return
(BufferedImage) image;
}
image =
new
ImageIcon(image).getImage();
boolean hasAlpha =
false
;
BufferedImage bimage =
null
;
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
try
{
int transparency = Transparency.OPAQUE;
if
(hasAlpha) {
transparency = Transparency.BITMASK;
}
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(
null
), image
.getHeight(
null
), transparency);
}
catch
(HeadlessException e) {
}
if
(bimage ==
null
) {
int type = BufferedImage.TYPE_INT_RGB;
if
(hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage =
new
BufferedImage(image.getWidth(
null
), image
.getHeight(
null
), type);
}
Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0,
null
);
g.dispose();
return
bimage;
}
}