62,623
社区成员
发帖
与我相关
我的任务
分享import java.awt.Image;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GrayImage extends JFrame{
//获取原始图片
public Image getOriImage(String path){
Image image = new ImageIcon(path).getImage();
return image;
}
//将图片image变灰,并返回变灰后的图片
public Image toGrayImage(Image image){
Image grayImage=null;
int w,h;
int[] pixels;
w=image.getWidth(null);
h=image.getHeight(null);
pixels=new int[w*h];
getPixels(image,0,0,w,h,pixels);
grayImage=createImage(new MemoryImageSource(w,h,pixels,0,w));
return grayImage;
}
//将原始图片的像素变灰,并放入pixels
public void getPixels(Image image,int x,int y,int w,int h,int[] pixels){
int gray;
PixelGrabber pg=new PixelGrabber(image,x,y,w,h,pixels,0,w);
try{
pg.grabPixels();
}catch(InterruptedException e){
System.err.print("Interrupted waiting for pixels!");
e.printStackTrace();
return;
}
for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
gray=(int)(((pixels[i*w+j]>>16)&0xff)*0.3);
gray+=(int)(((pixels[i*w+j]>>8)&0xff)*0.59);
gray+=(int)((pixels[i*w+j]&0xff)*0.11);
pixels[i*w+j]=(255<<24)|(gray<<16)|(gray<<8)|gray;
}
}
}
public static void main(String[] args) {
GrayImage gray = new GrayImage();
Image OriImage = gray.getOriImage("2.jpg"); //改成你自己图片的路径
Image grayImage = gray.toGrayImage(OriImage);
JLabel label = new JLabel();
label.setIcon(new ImageIcon(grayImage));
gray.getContentPane().add(label);
gray.pack();
gray.setDefaultCloseOperation(EXIT_ON_CLOSE);
gray.setVisible(true);
}
} for(int i=0;i<h;i++){
for(int j=0;j<w;j++){
gray=(int)(((pixels[i*w+j]>>16)&0xff)*0.3);
gray+=(int)(((pixels[i*w+j]>>8)&0xff)*0.59);
gray+=(int)((pixels[i*w+j]&0xff)*0.11);
if(gray>128) //改成你想要的阈值
gray = 255;
else
gray = 0;
pixels[i*w+j]=(255<<24)|(gray<<16)|(gray<<8)|gray;
}
}