这是我的代码:
protected void SaveMyImage_Click(object sender, EventArgs e)
{
string imageUrl = Hidden1.Value;
string saveLocation = Server.MapPath("~/PictureUploads/whatever2.png") ;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
顶部 imageUrl 声明正在接收 Base64 图像字符串,我想将其转换为图像。我认为我的代码集仅适用于“www.mysite.com/test.jpg”之类的图像,不适用于 Base64 字符串。有人有一些建议吗?谢谢!
这是一个示例,您可以修改该方法以接受字符串参数。然后只需使用 image.Save(...).
保存图像对象public Image LoadImage()
{
//data:image/gif;base64,
//this image is a single pixel (black)
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
当字节表示位图时,可能会出现异常
A generic error occurred in GDI+.
。如果发生这种情况,请在处理内存流之前保存图像(同时仍在 using 语句内)。
您可以直接将Base64保存到文件中:
string filePath = "MyImage.jpg";
File.WriteAllBytes(filePath, Convert.FromBase64String(base64imageString));
这就是我最终的结果。
private void SaveByteArrayAsImage(string fullOutputPath, string base64String)
{
byte[] bytes = Convert.FromBase64String(base64String);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Png);
}
我建议通过位图:
public void SaveImage(string base64)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save("SavingPath" + "ImageName.jpg");
}
}
}
就我而言,它仅适用于两行代码。测试以下 C# 代码:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";
byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);
就是这样。如果您确实发现此解决方案适合您,请投票。预先感谢。
这里是将图像从 Base64 字符串转换为
Image
对象并将其存储在具有唯一文件名的文件夹中的工作代码:
public void SaveImage()
{
string strm = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
//this is a simple white background image
var myfilename= string.Format(@"{0}", Guid.NewGuid());
//Generate unique filename
string filepath= "~/UserImages/" + myfilename+ ".jpeg";
var bytess = Convert.FromBase64String(strm);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
在类似的情况下,对我有用的是:
byte[] bytes = Convert.FromBase64String(Base64String);
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
ImageTagId
是ASP图像标签的ID。
如果您有一串 Base64 编码的二进制数据,您应该能够执行以下操作:
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
您应该能够将结果数组写入文件。
public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
try
{
string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string filePath = folder + "/" + FileName + "." + FileType;
File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
return true;
}
catch
{
return false;
}
}
使用
MemoryStream
不是一个好主意,并且违反了 MSDN 中关于 Image.FromStream()
的规范,它说
您必须在图像的生命周期内保持流打开。
ImageConverter
,例如:
public Image ConvertBase64ToImage(string base64)
=> (Bitmap)new ImageConverter().ConvertFrom(Convert.FromBase64String(base64));
在 NetCore
6.0
中,您可以在新的 File
类中使用 HttpClient 和异步方法。
实现非常简单:
static async Task DownloadFile(string imageUrl, string pathToSave)
{
var content = await GetUrlContent(url);
if (content != null)
{
await File.WriteAllBytesAsync(pathToSave, content);
}
}
static async Task<byte[]?> GetUrlContent(string url)
{
using (var client = new HttpClient())
using (var result = await client.GetAsync(url))
return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync():null;
}
用途:
await DownloadFile("https://example.com/image.jpg", @"c:\temp\image.jpg");
您可以使用以下代码将 Base64 字符串转换为图像并保存。此示例假设您正在使用控制台应用程序,但核心逻辑可以适用于其他类型的项目。
using System;
using System.Drawing;
using System.IO;
class Program
{
static void Main()
{
// Replace this string with your actual base64-encoded image
string base64String = "your_base64_encoded_string_here";
// Convert base64 to bytes
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert bytes to image
Image image = ConvertBytesToImage(imageBytes);
// Specify the path to save the image
string filePath = "path_to_save_image.png";
// Save the image to the specified path
SaveImage(image, filePath);
Console.WriteLine($"Image saved at: {filePath}");
}
static Image ConvertBytesToImage(byte[] imageBytes)
{
using (MemoryStream ms = new MemoryStream(imageBytes))
{
Image image = Image.FromStream(ms);
return image;
}
}
static void SaveImage(Image image, string filePath)
{
image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
}
}