在C语言中将图像转换为可用的字节数组?

3

有人知道如何在C或C++中将图像(特别是jpg)打开为字节数组吗?任何形式的帮助都将不胜感激。

谢谢!


1
什么样的字节数组?像素颜色的字节数组吗? - glebm
有什么意义呢?只有在某个地方绘制像素时,图像才会变得有趣。字节很无聊。如果必须使用字节,请使用FileStream + byte[(int)fs.Length]。 - Hans Passant
6个回答

2

ImageMagick 库也可以实现这一功能,它提供了足够的图像处理功能,您可以不需要将图像转换为字节数组并自己处理就能完成许多操作。


从介绍中:“仅推荐高级程序员使用” o_O - DerMike
1
@DerMike:这只是为了让初学者感觉更好一些,其实并不难 :-) - Malvineous

1

以下是我使用 GDIPlus 中定义的 Bitmap.LockBits 方法来完成的:

    Gdiplus::BitmapData bitmapData;
    Gdiplus::Rect rect(0, 0, bitmap.GetWidth(), bitmap.GetHeight());

    //get the bitmap data
    if(Gdiplus::Ok == bitmap.LockBits(
                        &rect, //A rectangle structure that specifies the portion of the Bitmap to lock.
                        Gdiplus::ImageLockModeRead | Gdiplus::ImageLockModeWrite, //ImageLockMode values that specifies the access level (read/write) for the Bitmap.            
                        bitmap.GetPixelFormat(),// PixelFormat values that specifies the data format of the Bitmap.
                        &bitmapData //BitmapData that will contain the information about the lock operation.
                        ))
    {
         //get the lenght of the bitmap data in bytes
         int len = bitmapData.Height * std::abs(bitmapData.Stride);

         BYTE* buffer = new BYTE[len];
         memcpy(bitmapData.Scan0, buffer, len);//copy it to an array of BYTEs

         //... 

         //cleanup
         pBitmapImageRot.UnlockBits(&bitmapData);       
         delete []buffer;
    }

1
你可以尝试使用DevIL图像库。我只在与OpenGL相关的事情中使用过它,但它也可以作为一个普通的图像加载库。

1

查看wxWidgets GUI Framework中的wxImage源代码。您很可能会对*nix发行版感兴趣。

另一个选择是GNU Jpeg库。


0

我让我的学生使用netpbm来表示图像,因为它带有方便的C库,但您也可以将图像转换成文本形式,手动创建等等。这里的好处是,您可以使用Unix方式的命令行工具将各种图像转换为PBM格式,而不仅仅是JPEG。包括JPEG Club在内的多个地方都提供了djpeg工具。即使经验相对较少的学生也可以编写一些相当复杂的程序。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接