在Swift中创建随机像素图像 [英] Create Random Pixel Images in Swift

查看:146
本文介绍了在Swift中创建随机像素图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想迅速创建一个随机像素生成器.

I want to create a random pixel generator in swift.

如何快速创建类似以下代码的内容?

How would I be able to create something like the below codes in swift?

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

Java program to demonstrate creation of random pixel image

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); 
        } 
    } 
} 

这是我唯一能实现的.从下面的代码中,您将知道我绝对是个敏捷的新手.

This is what I was only able to achieve. From the below code, you'll have know that i'm definitely a swift newbie.

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 {
        }
    }
}

推荐答案

这是针对macOS的解决方案(基于此iOS解决方案)创建一个NSImage:

Here's a solution for macOS (based on this iOS solution) that creates an 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.

To use this initializer, create an array of Pixel and then call NSImage passing in the pixels, width, and height. It returns an optional NSImage which is nil if anything went wrong creating the image.

用法示例:

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的便捷初始化程序.

Thanks to @LeoDabus for suggesting making the function a convenience initializer of NSImage.

这篇关于在Swift中创建随机像素图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆