对图片的操作:
internal static byte[] GetImageBinaryFromPath(string imageFullPath)
{
byte[] imageByte;
try
{
#region FromWeb
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imageSource);
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//if (request.HaveResponse)
//{
// if (response.StatusCode == System.Net.HttpStatusCode.OK)
// {
// Stream receiveStream = response.GetResponseStream();
// byte[] buffer = new byte[16 * 1024];
// using (MemoryStream ms = new MemoryStream())
// {
// int read;
// while (receiveStream != null && (read = receiveStream.Read(buffer, 0, buffer.Length)) > 0)
// {
// ms.Write(buffer, 0, read);
// }
// return ms.ToArray();
// }
// }
//}
#endregion
Image img = Image.FromFile(imageFullPath);
using (MemoryStream ms = new MemoryStream())
{
if (imageFullPath.ToLower().Contains(".jpg"))
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else if (imageFullPath.ToLower().Contains(".png"))
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
}
else
throw new Exception("Image Extension not match!");
return imageByte = ms.ToArray();
}
}
catch (Exception)
{ return null; }
}
internal static string CreateBase64Image(byte[] fileBytes, int width = 0, int height = 0)
{
Image streamImage;
/* Ensure we've streamed the document out correctly before we commit to the conversion */
using (MemoryStream ms = new MemoryStream(fileBytes))
{
streamImage = Image.FromStream(ms);
if (width > 0 && height > 0)
{
streamImage = ResizeImage(streamImage, width, height);
}
var memStream = new MemoryStream();
streamImage.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return Convert.ToBase64String(memStream.ToArray());
}
}
internal static Image ResizeImage(Image image, int width, int height)
{
Bitmap new_image = new Bitmap(width, height);
Graphics g = Graphics.FromImage((Image)new_image);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, width, height);
return new_image;
}
后台生成图片,保存到临时文件夹,返回图片的路径给前台即可。和上传图片的道理一样,先保存文件,后返回!
具体代码有吗
我有个验证码api是把图片转为字符串传递给前端使用的。
参考下:把图片转为base64字符串传递给前端,或者你搜搜别的方法
http://www.cnblogs.com/feiyun126/archive/2013/02/04/2892052.html
不需要保存成文件,这是浪费IO,直接内存创建Image,然后输出到流(或者也可以拿到writer,把内存流的write到此处也可以,反正效果差不多,都是内存流到网络流),最后记得把http头改一下就行了,即使你是传给客户端js解析(比如需要进行base64赋值),建议也不要在服务端做(浪费多),js是可以把此内容转换成该编码的。
eg1.
Page.render(writer)
{
create image;
image=>stream;
write(stream);
//if image show
=>change doc.mimetype;
}
提供2种方法:
1.后端可以生成一个图片地址,然后返回给前端
2.返回base64