java使用字符画一个海绵宝宝

2022-07-18,,,,

本文实例为大家分享了java使用字符画一海绵宝宝的具体代码,供大家参考,具体内容如下

用字符画一个海绵宝宝

用" “和”*"两个字符画出一个海绵宝宝,效果如下:

emm……效果可能不是很好,原图是这样的:

下面展示我的代码

代码

提示:代码仅供参考,大部分来自于网络

package package1;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.ioexception;
import javax.imageio.imageio;
public class imagedraw {
    public static void main(string[] args) throws ioexception {
        //需要使用哪种灰度化方式,就去掉那一行的注释"//"。
        //grayimage(1,"e:\\image.jpg");//最大值法灰度化 
        //grayimage(2,"e:\\image.jpg");//最小值法灰度化 
        //grayimage(3,"e:\\image.jpg");//平均值法灰度化
        //grayimage(4,"e:\\image.jpg");//加权法灰度化 
      }
    public static void grayimage(int status, string imagepath) throws ioexception {
        file file = new file(imagepath);
        bufferedimage image = imageio.read(file);
        int width = image.getwidth();
        int height = image.getheight();
        bufferedimage grayimage = new bufferedimage(width, height, image.gettype());
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int color = image.getrgb(j, i);
                final int r = (color >> 16) & 0xff;
                final int g = (color >> 8) & 0xff;
                final int b = color & 0xff;
                int gray = 0;
                if (status == 1) {
                    gray = getbigger(r, g, b);// 最大值法灰度化
                } else if (status == 2) {
                    gray = getsmall(r, g, b);// 最小值法灰度化
                } else if (status == 3) {
                    gray = getavg(r, g, b);// 均值法灰度化
                } else if (status == 4) {
                    gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);// 加权法灰度化
                }
                if(gray<=128) {
                    gray=0;
                    system.out.print("*");
                }else {
                    gray=255;
                    system.out.print(" ");
                }
            }
            system.out.println();
        }
    }
    // 比较三个数的大小
    public static int getbigger(int x, int y, int z) {
        if (x >= y && x >= z) {
            return x;
        } else if (y >= x && y >= z) {
            return y;
        } else if (z >= x && z >= y) {
            return z;
        } else {
            return 0;
        }
    }
    // 比较三个数的大小取最小数
    public static int getsmall(int x, int y, int z) {
        if (x <= y && x <= z) {
            return x;
        } else if (y >= x && y >= z) {
            return y;
        } else if (z >= x && z >= y) {
            return z;
        } else {
            return 0;
        }
    }
    // 均值法
    public static int getavg(int x, int y, int z) {
        int avg = (x + y + z) / 3;
        return avg;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《java使用字符画一个海绵宝宝.doc》

下载本文的Word格式文档,以方便收藏与打印。