当前位置: 移动技术网 > IT编程>开发语言>Java > java将图片至暗的实现方法

java将图片至暗的实现方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

之前也写过一个代码给一张图片然后把图片变暗,今天我们换一种思路,或者是是另外的一种方式将图片至暗,当然方法也是很简单的,但是对于菜鸟的我在这个地方停留了一天半的时间,将图片至暗

现在我们要将这样的一张图片

变成为

虽然说变暗之后确实没有之间亮的好看,但是不管了,反正那么漂亮的美女和我的关系我不太大,如果说硬是有关系的话,那应该是在梦中了,好了我们直接上代码

package com.epoint.wdg.test; 
 
import java.awt.color; 
import java.awt.image.bufferedimage; 
import java.io.file; 
import java.io.ioexception; 
 
import javax.imageio.imageio; 
 
public class imgtest { 
  public static void main(string[] args) throws ioexception { 
    file file=new file("c://users/wdg/desktop/people.png"); 
    //showparamterofimg(file); 
    file file2=changeimgtogray(file); 
    graypictobw(file2); 
  } 
  public static void getrgb(file file) throws ioexception{ 
    int []rgb =new int[3]; 
    bufferedimage img=imageio.read(file); 
    int pixel=img.getrgb(2, 3); 
    // 下面三行代码将一个数字转换为rgb数字  
    rgb[0] = (pixel & 0xff0000) >> 16;  
    rgb[1] = (pixel & 0xff00) >> 8;  
    rgb[2] = (pixel & 0xff);  
    system.out.println(rgb[0]+"-"+rgb[1]+"-"+rgb[2]); 
     
  } 
  //把图片变灰色 
  public static file changeimgtogray(file file) throws ioexception{ 
    float []rgb =new float[3]; 
    bufferedimage img=imageio.read(file); 
    //现在我需要获取到没一点的rgb 
    int y=img.getheight(); 
    int x=img.getwidth(); 
    bufferedimage grayimage = new bufferedimage(x, y, bufferedimage.type_byte_gray); 
    for(int i=0;i<x;i++){ 
      for(int j=0;j<y;j++){ 
        int pixel=img.getrgb(i, j); 
      // grayimage.setrgb(startx, starty, w, h, rgbarray, offset, scansize); 
         rgb[0] = (pixel & 0xff0000) >> 16;  
         rgb[1] = (pixel & 0xff00) >> 8;  
         rgb[2] = (pixel & 0xff);  
        int gray=(int) (rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11); 
         color color=new color(gray,gray,gray); 
         img.setrgb(i, j, color.getrgb()); 
 
      } 
    } 
    file newfile = new file("c://users/wdg/desktop/"+"/method5.jpg");  
    imageio.write(img, "jpg", newfile);  
    // graypictobw(newfile); 
    return newfile; 
  } 

其中最为重要的是这一部分:

int y=img.getheight(); 
int x=img.getwidth(); 
 
for(int i=0;i<x;i++){ 
  for(int j=0;j<y;j++){ 
    int pixel=img.getrgb(i, j); 
     rgb[0] = (pixel & 0xff0000) >> 16;  
     rgb[1] = (pixel & 0xff00) >> 8;  
     rgb[2] = (pixel & 0xff);  
    int gray=(int) (rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11); 
     color color=new color(gray,gray,gray); 
     img.setrgb(i, j, color.getrgb()); 
 
  } 
} 
  file newfile = new file("c://users/wdg/desktop/"+"/method5.jpg");  
  imageio.write(img, "jpg", newfile);  

这一部分是获取到到图片的每一点的像素或者说argb:

int pixel=img.getrgb(i, j); 

然后进一步的获取到rgb,然后我们获取到这点像素的灰度值,

int gray=(int) (rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11); 

并且创建一个颜色:

lor color=new color(gray,gray,gray); 

img.setrgb(i, j, color.getrgb()); 

这样我们将图片打印出来就是我们第二张图片那样了

以上这篇java将图片至暗的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网