[英]How can I use LZW algorithm to compress image, and after compress, how can I open it and see the result?
[英]how can I compress ASCII image after I convert it?
我需要編寫一個程序,將圖像轉換為ASCII代碼圖像我完成了第一步,但要求我需要壓縮圖像
我怎樣才能做到這一點? 我只知道我應該將每個10 * 10像素壓縮成一個
這是我的代碼
// A method to convert color image to grayscale image
public static BufferedImage toGrayScale(Image img)
{
// Convert image from type Image to BufferedImage
BufferedImage bufImg = convert(img);
// Scan through each row of the image
for(int j=0; j<bufImg.getHeight(); j++)
{
// Scan through each columns of the image
for(int i=0; i<bufImg.getWidth(); i++)
{
// Returns an integer pixel in the default RGB color model
int values=bufImg.getRGB(i,j);
// Convert the single integer pixel value to RGB color
Color oldColor = new Color(values);
int red = oldColor.getRed(); // get red value
int green = oldColor.getGreen(); // get green value
int blue = oldColor.getBlue(); // get blue value
// Convert RGB to grayscale using formula
// gray = 0.299 * R + 0.587 * G + 0.114 * B
double grayVal = 0.299*red + 0.587*green + 0.114*blue;
// Assign each channel of RGB with the same value
Color newColor = new Color((int)grayVal, (int)grayVal, (int)grayVal);
// Get back the integer representation of RGB color
// and assign it back to the original position
bufImg.setRGB(i, j, newColor.getRGB());
}
}
// return back the resulting image in BufferedImage type
return bufImg;
}
public static char[][] imageToASCII(Image img)
{
//convert the image to grayscale
BufferedImage bufImg = toGrayScale(img);
//get the width and height of the image
int width = bufImg.getWidth();
int height = bufImg.getHeight();
//These varibles are used to store the value of the colour model
int C1, C2, C3;
//create an array to store the output of each pixel
char[][] imageToASCII = new char[height][width];
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
//get the colour value of each pixel
int value = bufImg.getRGB(j, i);
//get the value in the Blue sector of RGB model
C1 = value & 255;
//get the value in the Green sector of RGB model
C2 = (value >> 8) & 255;
//get the value in the Red sector of RGB model
C3 = (value >> 16) & 255;
//calculate the average gray value
int g = (C1 + C2 + C3) / 3;
//check the given conditions and get the relative output
if (g >= 230)
imageToASCII[i][j] = ' ';
else if (g >= 200)
imageToASCII[i][j] = '.';
else if (g >= 180)
imageToASCII[i][j] = '*';
else if (g>= 160)
imageToASCII[i][j] = ':';
else if (g >= 130)
imageToASCII[i][j] = 'o';
else if (g >= 100)
imageToASCII[i][j] = '&';
else if (g >= 70)
imageToASCII[i][j] = '8';
else if (g >= 50)
imageToASCII[i][j] = '#';
else
imageToASCII[i][j] = '@';
}
}
//return the array
return imageToASCII;
}
}
如果要將其壓縮10( new width = old width/10
),則將此行添加到imageToASCII()
:
bufImg = convert(bufImg.getScaledInstance(bufImg.getWidth() / 10, bufImg.getHeight() / 24, BufferedImage.SCALE_SMOOTH));
此行將圖像轉換為較小的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.