js中将上传的图片转化成base64并传值到后台
$("#pc_file1").change(function () {
var file = $("#pc_file1").get(0).files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
// 图片格式为 base64
var base64 = e.target.result;
MachineInspection.base64 = base64;
}
});
将参数base64传入后台
string Dfile = "";
//服务器地址
string path = "D:\\FUSE\\UPLOAD_CJ_IMAGES";
int count = Directory.GetFiles(path).Count();
string name= DateTime.Now.ToString("yyyyMMddHHmmss");
string pathname = DateTime.Now.ToString("yyyyMMdd");
//log为原本图片文件后缀名
string filename = name+ log;
string fileno = "";
//判斷文件夾是否存在
if (!Directory.Exists(path + "\\" + pathname))
{
Directory.CreateDirectory(path + "\\" + pathname);
Dfile = path + "\\" + pathname + "\\" + filename;
}
else
{
//一个文件夹下最多放500张图片
int count1 = Directory.GetFiles(path + "\\" + pathname).Count();
if (count1 >= 500)
{
count += 1;
Directory.CreateDirectory(path + "\\" + (count).ToString());
Dfile = path + "\\" + (count).ToString() + "\\" + filename;
}
else
Dfile = path + "\\" + pathname + "\\" + filename;
}
try
{
//上传文件
GetPicThumbnail(base64, Dfile);
}
catch
{
Dfile = "";
return "err";
}
public void GetPicThumbnail(string Base64, string dFile)
{
byte[] buffer = Convert.FromBase64String(Base64.Substring(Base64.IndexOf(',') + 1));
int flag = 20;
MemoryStream stream = new MemoryStream(buffer);
Image iSource = Image.FromStream(stream);
ImageFormat tFormat = iSource.RawFormat;
int sW = 0, sH = 0;
int dHeight = iSource.Height, dWidth = iSource.Width;
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile
}
else
{
ob.Save(dFile, tFormat);
}
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
本文介绍如何使用JavaScript将用户选择的图片转换为Base64格式,并通过API将数据发送到后台服务器,包括读取文件、Base64编码和文件上传的步骤。

697

被折叠的 条评论
为什么被折叠?



