gpt4 book ai didi

c# - 如何遍历 .gif 图像中的每个像素?

转载 作者:可可西里 更新时间:2023-11-01 07:50:46 29 4
gpt4 key购买 nike

我需要遍历 .gif 图像并确定每个像素的 RGB 值、x 和 y 坐标。有人可以给我一个关于如何完成这个的概述吗? (方法、使用哪些命名空间等)

最佳答案

这是使用 LockBits() 和 GetPixel() 这两种方法的完整示例。除了 LockBits() 的信任问题之外,事情很容易变得棘手。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace BitmapReader
{
class Program
{
static void Main(string[] args)
{
//Try a small pic to be able to compare output,
//a big one to compare performance
System.Drawing.Bitmap b = new
System.Drawing.Bitmap(@"C:\Users\vinko\Pictures\Dibujo2.jpg");
doSomethingWithBitmapSlow(b);
doSomethingWithBitmapFast(b);
}

public static void doSomethingWithBitmapSlow(System.Drawing.Bitmap bmp)
{
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color clr = bmp.GetPixel(x, y);
int red = clr.R;
int green = clr.G;
int blue = clr.B;
Console.WriteLine("Slow: " + red + " "
+ green + " " + blue);
}
}
}

public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect,
System.Drawing.Imaging.ImageLockMode.ReadOnly,
bmp.PixelFormat);

IntPtr ptr = bmpData.Scan0;

int bytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];

System.Runtime.InteropServices.Marshal.Copy(ptr,
rgbValues, 0, bytes);

byte red = 0;
byte green = 0;
byte blue = 0;

for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
//See the link above for an explanation
//of this calculation
int position = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat)/8);
blue = rgbValues[position];
green = rgbValues[position + 1];
red = rgbValues[position + 2];
Console.WriteLine("Fast: " + red + " "
+ green + " " + blue);
}
}
bmp.UnlockBits(bmpData);
}
}
}

关于c# - 如何遍历 .gif 图像中的每个像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230188/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com