You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Photoshop脚本中获取指定单个像素的颜色?

嘿,我来帮你搞定这个获取单个像素颜色的需求!你想要的color = get.color.Pixel(x,y);这种简洁的调用方式,不同编程语言的实现思路略有不同,我给你整理了几个常用场景的代码实现:

Python 实现(基于Pillow库)

如果你用Python做桌面端的屏幕像素获取,Pillow库是个不错的选择:
首先安装依赖:

pip install pillow

然后封装成你想要的嵌套结构:

from PIL import ImageGrab

class get:
    class color:
        @staticmethod
        def Pixel(x, y):
            # 捕获整个屏幕的截图
            screen_shot = ImageGrab.grab()
            # 获取指定坐标的RGB颜色值,返回(R, G, B)元组
            return screen_shot.getpixel((x, y))

# 调用示例
color = get.color.Pixel(150, 300)
print(f"像素颜色RGB值:{color}")  # 输出类似(230, 230, 230)的结果
C# 实现(Windows桌面应用)

如果是在Windows Forms或WPF项目里,用C#可以直接调用系统API来实现:

using System.Drawing;
using System.Windows.Forms;

public static class get
{
    public static class color
    {
        public static Color Pixel(int x, int y)
        {
            // 创建1x1的Bitmap用于捕获指定坐标的屏幕像素
            using (Bitmap pixelBmp = new Bitmap(1, 1))
            {
                using (Graphics g = Graphics.FromImage(pixelBmp))
                {
                    // 把屏幕上(x,y)位置的像素绘制到Bitmap中
                    g.CopyFromScreen(x, y, 0, 0, new Size(1, 1));
                }
                // 返回该像素的Color对象,可通过.R/.G/.B获取分量
                return pixelBmp.GetPixel(0, 0);
            }
        }
    }
}

// 调用示例
Color targetColor = get.color.Pixel(200, 400);
System.Console.WriteLine($"R:{targetColor.R}, G:{targetColor.G}, B:{targetColor.B}");
JavaScript 实现(浏览器Canvas场景)

如果是在网页里获取Canvas画布上的像素,可以这样实现:

// 假设页面上有一个id为"myCanvas"的canvas元素
const get = {
    color: {
        Pixel: function(x, y) {
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            // 获取指定坐标的像素数据(RGBA格式)
            const pixelData = ctx.getImageData(x, y, 1, 1).data;
            // 返回结构化的颜色对象
            return {
                r: pixelData[0],
                g: pixelData[1],
                b: pixelData[2],
                a: pixelData[3]  // 透明度值
            };
        }
    }
};

// 调用示例
const canvasColor = get.color.Pixel(80, 80);
console.log(`Canvas像素颜色:R=${canvasColor.r}, G=${canvasColor.g}, B=${canvasColor.b}`);

注意:浏览器端JS出于安全限制,无法直接获取系统屏幕的像素,只能读取网页内Canvas或图片的像素;如果需要获取屏幕像素,得用Electron这类桌面JS框架结合Node.js截图工具实现。

内容的提问来源于stack exchange,提问作者lphd

火山引擎 最新活动