您的位置:首页 > 其它

为 FJCore 增加导出为 YV12、YUV444、RGB 的扩展方法

2014-02-15 01:50 525 查看
FJCore 是一款开源 JPEG 格式图片编解码库,该库使用 C# 实现,支持 Silverlight、WinForm、ASP.NET 等使用。

FJCore 设计的比较易于使用,性能也还不错。

FJCore: http://code.google.com/p/fjcore/

常规使用的代码就不贴了,百度搜一下就可以找到。

之前在项目中,需要把 JPEG 图片解码为 YV12 数据,所以用了这个库。

在使用的时候发现,JPEG 图片解码后的原数据存储在一个名为Raster的多维数组中,在网上找了很久,也只找到零星的资料,始终没搞明白如何把里面的数据保存为 YV12 或者 RGB 数据,后来经过多次测试,使用YUV工具分析比对,总算搞明白了,具体就不细说了,想了解的可以自己找个YUV工具去分析去。

代码:

public static class FjCoreExt
{
public static byte[] ToYv12(this Image image)
{
if (image.ColorModel.colorspace != ColorSpace.YCbCr)
{
image.ChangeColorSpace(ColorSpace.YCbCr);
}

int width = image.Width;
int height = image.Height;

var bytes = new byte[width*height*3/2];

int index = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
bytes[index] = image.Raster[0][j, i];
index++;
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
bytes[index] =
(byte)
((image.Raster[2][j, i] + image.Raster[2][j + 1, i] + image.Raster[2][j, i + 1] +
image.Raster[2][j + 1, i + 1])/4);
index++;
j++;
}
i++;
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
bytes[index] =
(byte)
((image.Raster[1][j, i] + image.Raster[1][j + 1, i] + image.Raster[1][j, i + 1] +
image.Raster[1][j + 1, i + 1])/4);
index++;
j++;
}
i++;
}

return bytes;
}

public static byte[] ToYuv444(this Image image)
{
if (image.ColorModel.colorspace != ColorSpace.YCbCr)
{
image.ChangeColorSpace(ColorSpace.YCbCr);
}

int width = image.Width;
int height = image.Height;

var bytes = new byte[width * height * 3];

var index = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
bytes[index] = image.Raster[0][j, i];
index++;
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
bytes[index] = image.Raster[1][j, i];
index++;
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
bytes[index] = image.Raster[2][j, i];
index++;
}
}

return bytes;
}

public static byte[] ToRgb(this Image image)
{
if (image.ColorModel.colorspace != ColorSpace.RGB)
{
image.ChangeColorSpace(ColorSpace.RGB);
}

int width = image.Width;
int height = image.Height;
var bytes = new byte[width * height * 3];
var index = 0;
for (int k = 0; k < height; k++)
{
for (int j = 0; j < width; j++)
{
for (int i = 0; i < image.Raster.Length; i++)
{
bytes[index] = image.Raster[i][j, k];
index++;
}
}
}

return bytes;
}
}


三个扩展方法,提供将Raster里的数据转换为 YV12、YUV444、RGB 的方法。

使用示例:

Stream stream = new FileStream("C:\\1.jpg",FileMode.Open);
FluxJpeg.Core.Decoder.JpegDecoder decoder = new JpegDecoder(stream);
var decodeImage = decoder.Decode();
var yv12Bytes = decodeImage.Image.ToYv12();
var yuv444Bytes = decodeImage.Image.ToYuv444();
var rgbBytes = decodeImage.Image.ToRgb();
stream.Close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐