C# 使用CryptoStream将位图转换为基本64字符串格式
我希望以Base64字符串格式返回图像的新数据 以下代码生成的图像文件格式不受支持C# 使用CryptoStream将位图转换为基本64字符串格式,c#,asp.net,image,bitmap,base64,C#,Asp.net,Image,Bitmap,Base64,我希望以Base64字符串格式返回图像的新数据 以下代码生成的图像文件格式不受支持 FileInfo imageFileName = new FileInfo(imageDirectoryFullName + "/image" + imageCounter.ToString() + "." + extension); try { RC2 crypt = RC2.Create(); ICryptoTransform transform
FileInfo imageFileName = new FileInfo(imageDirectoryFullName + "/image" +
imageCounter.ToString() + "." + extension);
try
{
RC2 crypt = RC2.Create();
ICryptoTransform transform = crypt.CreateEncryptor();
var output = new CryptoStream(File.Create(imageFileName.FullName),
transform,
CryptoStreamMode.Write);
imageInfo.Bitmap.Save(output, imageFormat);
}
catch (System.Runtime.InteropServices.ExternalException)
{
return null;
}
或
我如何才能做到这一点?您应该使用。然后可以将流转换为字节数组并馈送到。获取生成的字符串,并对其执行任意操作。我找到了函数
PerformCryptography
,从中获取icryptransform
,并可以将结果作为字节数组返回
从这里看,代码如下所示:
private void Start(object sender, EventArgs e)
{
try
{
// Step 01: First load the Image and convert to a byte array
var imgByteArray = File.ReadAllBytes(@"C:\someImage.jpg");
// Step 02: Then encrypt & convert to a byte array
RC2 crypt = RC2.Create();
ICryptoTransform transform = crypt.CreateEncryptor();
var cryptByteArray = PerformCryptography(transform, imgByteArray);
// Step 03: Now convert the byte array to a Base64 String
string base64String = Convert.ToBase64String(cryptByteArray);
}
catch (System.Runtime.InteropServices.ExternalException)
{
//return null;
}
}
以下是支持功能:
private byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
什么是imageInfo
?在你的问题中没有关于它的信息,而且它似乎是导致它的原因。为什么你要费心阅读图像,然后重新保存它呢?你可以,呃,读取文件并使用这些字节。字面意思就是File.ReadAllBytes(文件路径)
。特别是因为image.RawFormat
只是将其重新保存为与读取时完全相同的格式。Hi@Nyerguds。那是个好地方。我将更新答案,因为这是更有效的方法
private byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}