图片与Json(String)的转换
将C#的读取的文件转换为Json的字符串,然后使用JS显示出来。
1.Img 2 Json
1 //图片 转为 base64编码的文本 2 private void ImgToBase64String(string Imagefilename) 3 { 4 try 5 { 6 MemoryStream ms = new MemoryStream(this.FileUpload1.FileBytes); 7 byte[] arr = new byte[ms.Length]; 8 ms.Position = 0; 9 ms.Read(arr, 0, (int)ms.Length); 10 ms.Close(); 11 String strbaser64 = Convert.ToBase64String(arr); 12 this.TextBox1.Text = strbaser64; 13 } 14 catch (Exception ex) 15 { 16 lbl_message.Text = "ImgToBase64String 转换失败\nException:" + ex.Message; 17 } 18 }
2 Json 2 Img
1 <script type="text/javascript"> 2 function imgfun() 3 { 4 var result = $("#TextBox1").val(); 5 if (result.indexOf("<img",0) < 0) 6 { 7 $("#TextBox1").val('<img src="data:image/bmp;base64,' + result + '" alt="图片Base64编码" style="max-width:90%; max-height:2000px;"/>'); 8 } 9 $("#img_area").html('' + $("#TextBox1").val() + ''); 10 } 11 </script>
3 HMTL
1 <div> 2 3 <asp:FileUpload ID="FileUpload1" runat="server" Width="403px" /> 4 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> 5 <input type="button" id="btn2" onclick="imgfun()" value="Button" /> 6 7 </div> 8 <div> 9 <asp:Label ID="lbl_message" runat="server" Text=""></asp:Label> 10 </div> 11 <div> 12 <input type="image" id="input_img" runat="server" /></div> 13 <div> 14 <asp:TextBox ID="TextBox1" runat="server" Height="200px" TextMode="MultiLine" Width="100%"></asp:TextBox></div> 15 <div> 16 <p id="img_area"> </p> 17 18 </div>