在Apple Swift中将图像转换为2D数组(或等效的)



我想知道如何把一个UIImage变成可用和可修改的东西。Java代码来处理我需要的东西看起来像这样:

BufferedImage img= ImageIO.read(file);
Raster raster=img.getData();
int w=raster.getWidth(),h=raster.getHeight();
int pixels[][]=new int[w][h];
for (int x=0;x<w;x++)
{
    for(int y=0;y<h;y++)
    {
        pixels[x][y]=raster.getSample(x,y,0);
    }
}

我需要通过访问图像中的每个像素来修改图像的alpha值。

未经测试,但我认为这将工作或应该非常接近。

import UIKit
import CoreGraphics

var uiimage = UIImage(contentsOfFile: "/PATH/TO/image.png")
var image = uiimage.CGImage

let width = CGImageGetWidth(image)
let height = CGImageGetHeight(image)
let colorspace = CGColorSpaceCreateDeviceRGB()
let bytesPerRow = (4 * width);
let bitsPerComponent :UInt = 8
let pixels = UnsafePointer<UInt8>(malloc(width*height*4))

var context = CGBitmapContextCreate(pixels, width, height, bitsPerComponent, bytesPerRow, colorspace,
  CGBitmapInfo());
CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), image)

for x in 0..width {
  for y in 0..height {
    //Here is your raw pixels
    let offset = 4*((Int(width) * Int(y)) + Int(x))
    let alpha = pixels[offset]
    let red = pixels[offset+1]
    let green = pixels[offset+2]
    let blue = pixels[offset+3]
  }
}

如果你真的需要转换成2D数组,可以通过CGContext将图像渲染成字节数组,然后将数组分割成部分。CGContext使用0…255颜色范围,而不是0…字节数组将采用rgba格式。

转换为0…的示例代码:

import UIKit
import CoreGraphics
func pixelData() -> [UInt8]? {
    let dataSize = size.width * size.height * 4
    var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let context = CGContext(data: &pixelData,
                            width: Int(size.width),
                            height: Int(size.height),
                            bitsPerComponent: 8,
                            bytesPerRow: 4 * Int(size.width),
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
    guard let cgImage = self.cgImage,
          let context = context else { return nil }
    context.draw(cgImage, in: CGRect(origin: .zero, size: size))
    
    return pixelData
}

func pixelMatrix() -> [[[Float]]]? {
    guard let pixels = pixelData() else {
        return nil
    }
    var data: [[[Float]]] = []
    
    let width = Int(size.width)
    let height = Int(size.height)
    
    for y in 0..<height {
        var row: [[Float]] = []
        for x in 0..<width {
            let offset = 4 * ((width * y) + x)
            
            let red = Float(pixels[offset]) / 255
            let green = Float(pixels[offset + 1]) / 255
            let blue = Float(pixels[offset + 2]) / 255
            let alpha = Float(pixels[offset + 3]) / 255
            let pixel = [red, green, blue, alpha]
            row.append(pixel)
        }
        data.append(row)
    }
    return data
}

相关内容

  • 没有找到相关文章

最新更新