你好,我正在尝试从图像中获取像素值,将图像转换为灰度并最终通过UIImage
从字节数组返回NSData
。但它返回null
partial void Analyze_button_TouchUpInside(UIButton sender)
{
int Rows = 324; //Width
int Cols = 182; //Height
var ImageSize = Rows * Cols;
AimageBytes = new byte[ImageSize];
RimageBytes = new byte[ImageSize];
GimageBytes = new byte[ImageSize];
BimageBytes = new byte[ImageSize];
GreyImageBytes = new byte[ImageSize];
var pixels = GetPixels(img);
for (ind = 0; ind < ImageSize; ind++)
{
pval = pixels[ind];
AimageBytes[ind] = (byte)((pval & 0xFF000000) >> 24);
RimageBytes[ind] = (byte)((pval & 0x00FF0000) >> 16);
GimageBytes[ind] = (byte)((pval & 0x0000FF00) >> 8);
BimageBytes[ind] = (byte)(pval & 0x000000FF);
GreyImageBytes[ind] = (byte)((RimageBytes[ind] + GimageBytes[ind] + BimageBytes[ind]) / 3);
}
var dataTest = NSData.FromArray(GreyImageBytes);
var ImageTest = UIImage.LoadFromData(dataTest);
PlantPhoto.Image = ImageTest;
}
用于获取像素的方法:
public static int[] GetPixels(UIImage image)
{
const CGBitmapFlags flags = CGBitmapFlags.ByteOrder32Big | CGBitmapFlags.PremultipliedLast;
var width = (int)image.CGImage.Width;
var height = (int)image.CGImage.Height;
var bytesPerPixel = image.CGImage.BitsPerPixel;
var bytesPerRow = bytesPerPixel * width;
var bitsPerComponent = image.CGImage.BitsPerComponent;
var buffer = new byte[bytesPerRow * height];
var pixels = new int[width * height];
var handle = GCHandle.Alloc(buffer);
try
{
using (var colorSpace = CGColorSpace.CreateGenericRgb())
using (var context = new CGBitmapContext(buffer, width, height, bitsPerComponent, bytesPerRow, colorSpace, flags))
context.DrawImage(new RectangleF(0, 0, width, height), image.CGImage);
for (var y = 0; y < height; y++)
{
var offset = y * width;
for (var x = 0; x < width; x++)
{
var idx = bytesPerPixel * (offset + x);
var r = buffer[idx + 0];
var g = buffer[idx + 1];
var b = buffer[idx + 2];
var a = buffer[idx + 3];
pixels[x * y] = a << 24 | r << 16 | g << 8 | b << 0;
}
}
}
finally
{
handle.Free();
}
return pixels;
}
答案 0 :(得分:0)
我正在尝试确定数据格式是否不同于与uiimage数据参数匹配的格式。不幸的是,我必须使用我发布的方法。 试图将图像转换为字节数组然后返回,它可以工作。
NSData imageDataTest = img.AsPNG();
Byte[] testByteArray = new Byte[imageDataTest.Length];
Marshal.Copy(imageDataTest.Bytes, testByteArray, 0, Convert.ToInt32(imageDataTest.Length));
UIImage backToImage = UIImage.LoadFromData(imageDataTest);
testByteArray 和 GreyImageBytes 似乎在字节数组中具有相同的结构。