3

当我尝试在 c# 中使用 memorystream 保存图像时,出现下面提到的错误。仅当字节数组 byteImageData 长度等于 24000 时才会引发错误,否则代码工作正常。下面是代码片段:

string strDbConn = string.Empty;
string strImageFileName = string.Empty;
string strImageData = string.Empty;
DataSet imageDS = new DataSet();
Byte[] byteImageData = new Byte[0];
Image saveImage;
string strImgSavePath = string.Empty;
try
{
    //---open the database connection
    strDbConn = ConfigurationSettings.AppSettings["DBConnection"].ToString().Trim();
    SqlConnection dbcon = new SqlConnection(strDbConn);
    dbcon.Open();
    SqlDataAdapter imageSqlDataAdapter = new SqlDataAdapter("select * from image_data", dbcon);
    imageSqlDataAdapter.Fill(imageDS);
    dbcon.Close();
    for (int i = 0; i < imageDS.Tables[0].Rows.Count; i++)
    {
        strImageFileName = imageDS.Tables[0].Rows[i]["name"].ToString().Trim();
        strImageData = imageDS.Tables[0].Rows[i]["signature_vod__c"].ToString().Trim();
        //converting string to byte array
        byteImageData = Convert.FromBase64String(strImageData);
        //---create Memory stremm from the Image Byte data
        MemoryStream stmImageData = new MemoryStream(byteImageData);
        //--saving the image
        saveImage = Image.FromStream(stmImageData);
        strImgSavePath = ConfigurationSettings.AppSettings["ImageSavePath"].ToString().Trim();
        saveImage.Save(strImgSavePath + strImageFileName + ".jpeg"); // error comes here
        //stmImageData.Close();
    }
}
catch (Exception ex)
{

}

抛出的错误是:

Messgae = A generic error occurred in GDI+. 
Inner Exception = null 

堆栈跟踪:

at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
   at System.Drawing.Image.Save(String filename, ImageFormat format)
   at System.Drawing.Image.Save(String filename)
   at VeevaImageApp.Program.CreateAndSaveImageusingDataSet2() in Program.cs:line 141

仅当字节数组 byteImageData 长度为 24000 时才会出现错误,否则代码工作文件 - 可能是什么问题,我该如何解决?

4

1 回答 1

0

图像数据是什么格式的?如果它已经是 JPG,你应该只使用File.WriteAllBytes(path, byteImageData). 如果你真的需要转换,你应该使用更新的图像编码器/解码器类:在网上搜索 JpegBitmapEncoder 或 PngBitmapEncoder 的信息。(如果这些是照片或扫描我们的JPEG,否则使用PNG。)

于 2012-10-25T16:08:05.550 回答