java 如何水平翻转图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12562680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:23:14  来源:igfitidea点击:

How to flip an image horizontally

javainvert

提问by Judy Tran

HiI was wondering how to flip and image horizontally, for a practce task I was given a code that reads an image, inverting it to an image indicating it's brightness from 0-5, I had to flip an image.

嗨,我想知道如何水平翻转和图像,对于练习任务,我得到了一个读取图像的代码,将其反转为指示其亮度从 0 到 5 的图像,我不得不翻转图像。

This is my code of my reading an image and drawing it

这是我阅读图像并绘制它的代码

    public int[][] readImage(String url) throws IOException
{
    // fetch the image
    BufferedImage img = ImageIO.read(new URL(url));

    // create the array to match the dimensions of the image
    int width = img.getWidth();
    int height = img.getHeight();
    int[][] imageArray = new int[width][height];

    // convert the pixels of the image into brightness values
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            // get the pixel at (x,y) 

            int rgb = img.getRGB(x,y);
            Color c = new Color(rgb);
            int red = c.getRed();
            int green = c.getGreen();
            int blue = c.getBlue();

            // convert to greyscale
            float[] hsb = Color.RGBtoHSB(red, green, blue, null);                
            int brightness = (int)Math.round(hsb[2] * (PIXEL_CHARS.length - 1));

            imageArray[x][y] = brightness;
        }
    }
    return imageArray;
}

public void draw() throws IOException
{
    int[][] array = readImage("http://sfpl.org/images/graphics/chicklets/google-small.png");
    for(int i=0; i<array.length; i++)
    {
        for(int pic=0; pic<array[i].length; pic++)
        {
            if(array[pic][i] == 0)
            {
                System.out.print("X");
            }
            else if(array[pic][i] == 1)
            {
                System.out.print("8");
            }

            else if(array[pic][i] == 2)
            {
                System.out.print("0");
            }       

            else if(array[pic][i] == 3)
            {
                System.out.print(":");
            }

            else if(array[pic][i] == 4)
            {
                System.out.print(".");
            }

            else if (array[pic][i] == 5)
            {
                System.out.print(" ");
            }

            else 
            {
                System.out.print("error");
                break;
            }   

        }
        System.out.println();
    }
}    

and this is the code I tried to create to horizontally flip it,

这是我尝试创建的用于水平翻转它的代码,

void mirrorUpDown()
{
    int[][] array = readImage("http://sfpl.org/images/graphics/chicklets/google-small.png");
    int i = 0;

    for (int x = 0; x < array.length; x++)
    {
        for (int y = 0; y < array[i].length; y++)
        {{
                int temp = array[x][y]; 
                array[x][y]= array[-x][y]; 
                array[array[i].length-x][y]=temp;
            }
        }
    }

}    

I get an error

我收到一个错误

 unreported exception java.io.IException;
 must be caught or declared to be thrown

回答by eProw

I'd actually do it by this way...

我真的会这样做...

    BufferedImage flip(BufferedImage sprite){
        BufferedImage img = new BufferedImage(sprite.getWidth(),sprite.getHeight(),BufferedImage.TYPE_INT_ARGB);
        for(int xx = sprite.getWidth()-1;xx>0;xx--){
            for(int yy = 0;yy < sprite.getHeight();yy++){
                img.setRGB(sprite.getWidth()-xx, yy, sprite.getRGB(xx, yy));
            }
        }
    return img;
}

Just a loop whose x starts at the end of the first image and places its rgba value on the flipped position of the second image. Clean, easy code :)

只是一个循环,其 x 从第一张图像的末尾开始,并将其 rgba 值放在第二张图像的翻转位置上。干净,简单的代码:)

回答by Mukul Goel

The function mirrorUpDown() , add a throws IOException there.

函数 mirrorUpDown() ,在那里添加一个 throws IOException 。

Also the function from which you are calling these methods, does that handle exception, does that code enclosed in a try catch block or the function is also set to throw IOException (one of either should be there)

此外,您调用这些方法的函数,是否处理异常,是否包含在 try catch 块中的代码,或者该函数是否也设置为抛出 IOException (其中之一应该在那里)

回答by Alix Martin

How is your image supposed to know it should get it's data from imageArray ?

您的图像应该如何知道它应该从 imageArray 获取数据?

instead, you should access the raster of your image and modify the data in it.

相反,您应该访问图像的光栅并修改其中的数据。

void flip(BufferedImage image) {
         WritableRaster raster = image.getRaster();
         int h = raster.getHeight();
         int w = raster.getWidth();
         int x0 = raster.getMinX();
         int y0 = raster.getMinY();
         for (int x = x0; x < x0 + w; x++){
             for (int y = y0; y < y0 + h / 2; y++){
                 int[] pix1 = new int[3];
                 pix1 = raster.getPixel(x, y, pix1);
                 int[] pix2 = new int[3];
                 pix2 = raster.getPixel(x, y0 + h - 1 - (y - y0), pix2);
                 raster.setPixel(x, y, pix2);
                 raster.setPixel(x, y0 + h - 1 - (y - y0), pix1);
             }
         }
         return;
    }

回答by Richard Kenneth Niescior

Sorry about posting this here over a year later but it should aid someone at a stage

很抱歉一年多后在这里发布此信息,但它应该会在某个阶段帮助某人

   try{
   java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read(getClass().getResource("Your image bro.jpg")) ;
 int[] h = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), null, 0, bi.getWidth());
 int [] h1 = new int[h.length];
 System.out.println(""+h.length);
  for(int j = 0;500>j;j++){
   for(int i = 500;i>0;i--){
         h1[j*500+(500-i)] = h[(j*500)+(i-1)];
   }
  }
 bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), h1, 0, bi.getWidth());
      }
      catch(Exception e){e.printStackTrace();}

Lets break the code down

让我们分解代码

java.awt.image.BufferedImage bi =javax.imageio.ImageIO.read(getClass().getResource("Your image bro.jpg"));

Tries to read the image and stores the read image into the BufferedImage variable bi

尝试读取图像并将读取的图像存储到 BufferedImage 变量 bi

  int[] h = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), null, 0, bi.getWidth());
  int [] h1 = new int[h.length];

instantiate two arrays, h is the original RGB Array and h1 will be the horizontally flipped RGB array.

实例化两个数组,h 是原始 RGB 数组,h1 将是水平翻转的 RGB 数组。

for(int j = 0;500>j;j++){
 for(int i = 500;i>0;i--){
  h1[j*500+(500-i)] = h[(j*500)+(i-1)];
 }
}

Lets look at something in particular more closely

让我们更仔细地看一些特别的东西

  h1[j*500+(500-i)] = h[(j*500)+(i-1)];

Images are scanned from position 0;0 to x.length;y.length but it is scanned in a coninual array. Thus we use a psuedo-array to manipulate the flipping of the image. j*500 references the Y values and (500-i) references the x values.

图像从位置 0;0 到 x.length;y.length 扫描,但它以连续阵列扫描。因此,我们使用伪数组来操纵图像的翻转。j*500 引用 Y 值,(500-i) 引用 x 值。

 bi.setRGB(0, 0, bi.getWidth(), bi.getHeight(), h1, 0, bi.getWidth());

Finally, the image gets stored back into the BufferedImage variable.

最后,图像被存储回 BufferedImage 变量。

Note that the 500 constant is referencing your x resolution of the image. For example, 1920 x 1080 sized image uses a max value of 1920. The logic is yours to decide.

请注意,500 常量是指图像的 x 分辨率。例如,1920 x 1080 大小的图像使用最大值 1920。逻辑由您决定。