我正在嘗試驗證以 Base64 字符串格式提交到后端的圖像,方法是將其解析為 Image 對象,從同一 Image 對象中提取它,最后比較輸入字節數組和輸出字節數組,假設這兩個應該相同或有一些東西輸入圖像錯誤。這是代碼: private void UpdatePhoto(string photoBase64) { var imageDataInBytes = Convert.FromBase64String(photoBase64); ValidateImageContent(imageDataInBytes); } private void ValidateImageContent(byte[] imageDataInBytes) { using (var inputMem = new MemoryStream(imageDataInBytes)) { var img = Image.FromStream(inputMem, false, true); using (MemoryStream outputMemStream = new MemoryStream()) { img.Save(outputMemStream, img.RawFormat); var outputSerialized = outputMemStream.ToArray(); if (!outputSerialized.SequenceEqual(imageDataInBytes)) throw new Exception("Invalid image. Identified extra data in the input. Please upload another photo."); } } }它在我知道是有效的圖像上失敗了。我的假設是否錯誤,即 Image.Save 的輸出必須與 Image.FromStream 的輸出相同?有沒有辦法糾正這個邏輯以正確實現這種驗證方式?
System.Drawing.Image Save 的輸出與輸入 Image.FromStream
慕尼黑8549860
2023-07-09 17:38:15