iT邦幫忙

0

C# mssql 有存圖片的varbinary欄位我要怎麼還原成jpg檔案

mssql 有存圖片的varbinary欄位
我要怎麼還原成jpg檔案,將檔案暫存在exe檔的資料夾下

因為我有個功能要做
將DB內的二進位圖檔 還原成jpg檔壓上浮水印之類的操作,再變成varbinary存入DB 新欄位(浮水印圖)

我該如何用linq+C# 做到呢

1 個回答

2
通靈亡
iT邦研究生 5 級 ‧ 2020-06-13 14:11:36
最佳解答
// Varbinary => Image
public Image ConvertToImage(System.Data.Linq.Binary linqBinary)
{
    byte[] picBinary = linqBinary.ToArray();
    Image image = null;

    using (MemoryStream ms = new MemoryStream(picBinary))
    {
        image = Image.FromStream(ms);
    }
    return image;
}

// Image => Byte[]
public byte[] ImageToByteArray(System.Drawing.Image image)
{
   using (MemoryStream ms = new MemoryStream())
   {
      image.Save(ms,image.RawFormat);
      return  ms.ToArray();
   }
}

// Save Image As File
Image image = ConvertToImage(photoBinary);
image.Save("output.jpg", ImageFormat.Jpeg);


// Insert Image As Varbinary To Database
byte[] imageBinary = ImageToByteArray(image);
using(SqlConnection connection = new SqlConnection(/* Connection String */))
using(SqlCommand command = new SqlCommand(query, connection))
{
    connection.Open();
    
    string query = "INSERT INTO Table(Content) VALUES(@Content)";
    
    SqlParameter param = command.Parameters.Add("@Content", SqlDbType.VarBinary);
    param.Value = imageBinary;

    command.ExecuteNonQuery();  
}
subisu99 iT邦新手 5 級 ‧ 2020-06-15 14:24:04 檢舉

謝謝~ 雖然不知道是不是讀取權限的問題會出現GDI 泛型錯誤
後改寫為這樣就好了

public void ConvertToOCRImage(byte[] picBinary)
       {
           string imagePath = @"D:\source\NEWGIT\" + "\\ouputOCR.jpg";
           Image image = null;
           using (MemoryStream ms = new MemoryStream(picBinary))
           {
               image = Image.FromStream(ms);
               image.Save(imagePath, ImageFormat.Jpeg);
               using (System.IO.FileStream oFS = System.IO.File.Open(imagePath, FileMode.OpenOrCreate))
               {
                   oFS.Write(ms.ToArray(), 0, ms.ToArray().Length);
               }
           }
       }
        ```

我要發表回答

立即登入回答