【问题标题】:Create Random Pixel Images in Swift在 Swift 中创建随机像素图像
【发布时间】:2020-10-03 08:41:39
【问题描述】:

我想在 swift 中创建一个随机像素生成器。

我怎样才能在 swift 中创建类似以下代码的内容?

演示随机像素图像创建的Java程序

import java.io.File; 
import java.io.IOException; 
import java.awt.image.BufferedImage; 
import javax.imageio.ImageIO; 
public class RandomImage 
{ 
    public static void main(String args[])throws IOException 
    { 
        // Image file dimensions 
        int width = 640, height = 320; 

        // Create buffered image object 
        BufferedImage img = null; 
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 

        // file object 
        File f = null; 

        // create random values pixel by pixel 
        for (int y = 0; y < height; y++) 
        { 
            for (int x = 0; x < width; x++) 
            { 
                int a = (int)(Math.random()*256); //generating 
                int r = (int)(Math.random()*256); //values 
                int g = (int)(Math.random()*256); //less than 
                int b = (int)(Math.random()*256); //256 

                int p = (a<<24) | (r<<16) | (g<<8) | b; //pixel 

                img.setRGB(x, y, p); 
            } 
        } 

        // write image 
        try
        { 
            f = new File("G:\\Out.jpg"); 
            ImageIO.write(img, "jpg", f); 
        } 
        catch(IOException e) 
        { 
            System.out.println("Error: " + e); 
        } 
    } 
} 

这是我只能实现的。从下面的代码中,你就会知道我绝对是一个快速的新手。

import Cocoa

class ViewController: NSViewController {

                let height=500
                let width=500
                for y in 0..<height {
                    for x in 0..<width {

                    }
                }



    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        }
    }
}

【问题讨论】:

    标签: java swift image image-processing pixel


    【解决方案1】:

    你可以使用下面的函数来创建随机的 UIImage

        public struct PixelData {
            var a: UInt8
            var r: UInt8
            var g: UInt8
            var b: UInt8
        }
    
        func createRandomUIImage(width: Int, height: Int) -> UIImage? {
            var pixels = [PixelData]()
            let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
            let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
            let bitsPerComponent = 8
            let bitsPerPixel = 32
    
            for _ in 0..<width {
                for _ in 0..<height {
                    pixels.append(PixelData(a: .random(in: 0...255), r: .random(in: 0...255), g: .random(in: 0...255), b: .random(in: 0...255)))
                }
            }
    
            guard let providerRef = CGDataProvider(data: NSData(bytes: &pixels,
                                    length: pixels.count * MemoryLayout<PixelData>.size)
                )
                else { return nil }
    
            guard let cgim = CGImage(
                width: width,
                height: height,
                bitsPerComponent: bitsPerComponent,
                bitsPerPixel: bitsPerPixel,
                bytesPerRow: width * MemoryLayout<PixelData>.size,
                space: rgbColorSpace,
                bitmapInfo: bitmapInfo,
                provider: providerRef,
                decode: nil,
                shouldInterpolate: true,
                intent: .defaultIntent
                )
                else { return nil }
    
            return UIImage(cgImage: cgim)
        }
    

    【讨论】:

    • 1) OP 将需要 NSImage 而不是 UIImage 才能在 macOS 中使用。请注意,OP 正在导入 cocoa 并创建一个NSViewController。 2)您正在使用我的其他答案之一中的代码而没有信用。
    • 我认为这里的重点是帮助 OP。我已经对代码进行了修改并检查它是否适用于 XCode。我没有注意到 OP 导入了 Cocoa。 OP 可以接受任何适合它的答案。
    【解决方案2】:

    这是一个针对 macOS 的解决方案(基于 this iOS solution),它创建了一个 NSImage

    public struct Pixel {
        var a,r,g,b: UInt8
    }
    
    extension NSImage {
        convenience init?(pixels: [Pixel], width: Int, height: Int) {
            guard width > 0 && height > 0, pixels.count == width * height else { return nil }
            var data = pixels
            guard let providerRef = CGDataProvider(data: Data(bytes: &data, count: data.count * MemoryLayout<Pixel>.size) as CFData)
                else { return nil }
            guard let cgim = CGImage(
                width: width,
                height: height,
                bitsPerComponent: 8,
                bitsPerPixel: 32,
                bytesPerRow: width * MemoryLayout<Pixel>.size,
                space: CGColorSpaceCreateDeviceRGB(),
                bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
                provider: providerRef,
                decode: nil,
                shouldInterpolate: true,
                intent: .defaultIntent)
            else { return nil }
            self.init(cgImage: cgim, size: NSSize(width: width, height: height))
        }
    }
    

    要使用此初始化程序,请创建一个 Pixel 数组,然后调用 NSImage,传入 pixelswidthheight。它返回一个可选的NSImage,即nil,如果在创建图像时出现任何问题。

    示例用法:

    let height = 500
    let width = 500
    
    var pixels: [Pixel] = .init(repeating: .init(a: 0, r: 0, g: 0, b: 0), count: width * height)
    for index in pixels.indices {
        pixels[index].a = 255
        pixels[index].r = .random(in: 0...255)
        pixels[index].g = .random(in: 0...255)
        pixels[index].b = .random(in: 0...255)
    }
    let image = NSImage(pixels: pixels, width: width, height: height)
    

    感谢@LeoDabus 建议将该函数作为NSImage 的便捷初始化器。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多