【发布时间】:2021-11-19 09:22:59
【问题描述】:
我正在尝试编写灰度代码。我基本上是这样写的,但我不明白如何在这段代码中使用 Marshal 或 lockbits 来提高速度。(我选择这种方法是因为使用的指针对我来说更复杂)我写了一些东西,但我知道代码太多或丢失了。我知道我应该使用 lockbits 而不是 getpixel 以加快速度,但我很困惑。这对我来说很复杂,可能我在错误的地方使用它们。
编辑:我正在尝试将照片变为灰色。它正在编译,但没有变灰,我不明白代码有什么问题。
编辑:我知道答案在下面,但我想学习用 Lockbites 和 Marshal.Copy 函数编写这个。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace dnm2709normalimg
{
class GrayFilter
{
public static Bitmap DoGray(Bitmap bmp)
{
for (int i = 0; i < bmp.Height; i++)
{
for (int j = 0; j < bmp.Width; j++)
{
int value = (bmp.GetPixel(j, i).R + bmp.GetPixel(j, i).G + bmp.GetPixel(j, i).B) / 3;
Color clr;
clr = Color.FromArgb(value, value, value);
BitmapData bmpData =bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),ImageLockMode.ReadOnly, bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
Marshal.Copy(ptr, rgbValues, 0, bytes);
// Set every third value to 255. A 24bpp bitmap will look red.
for (int counter = 2; counter < rgbValues.Length; counter += 3)
rgbValues[counter] = 255;
// Copy the RGB values back to the bitmap
Marshal.Copy(rgbValues, 0, ptr, bytes);
bmp.UnlockBits(bmpData);
}
}
return bmp;
}
}
}
【问题讨论】:
-
您的实际问题是什么?你得到什么结果?你会期待什么结果?另外:“应该使用 lockbits 而不是 getpixel”,是的,如果你需要性能。在许多情况下,获取/设置像素非常好,例如,如果代码很少使用或图像很小。
-
实际上我是这方面的新手,但对于该项目,我应该使用更快的方法,但老实说,我无法清楚地了解主题。很难找到来源,或者我找不到我的主要语言.所以我问这个问题是为了了解我应该使用lockbit和marshall的哪个部分。我在代码中做错了并且正在工作但使用了错误的方式。
-
但是 什么 的工作方式不对? 得到什么结果?说明代码“工作但以错误的方式”并不能帮助我们提供答案。请更新问题,而不是在 cmets 中添加信息。
-
好的。我要去那里写。
-
请用回答问题所需的额外信息更新(编辑)您的问题。祝你好运???
标签: c# image-processing