无法从数据库中检索图像?

时间:2013-07-29 10:28:24

标签: asp.net mysql image

我正在开发应用程序,我想捕获图像并存储在数据库中ANA再次想要在网页上检索图像,我尝试此代码

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {

            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq=strm.Read(buffer, 0, 2048);
        }
    }

    public Stream DisplayImage(int theID)
    {
        DB_Connection();

        string sql = "SELECT Image_Data FROM Image_T WHERE Img_ID = '" + theID + "'";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("Img_ID", theID);

        object imgg = (byte[])cmd.ExecuteScalar(); 
        //byte[] imagedata = (byte[])cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])imgg);
        }
        catch
        {
            return null;
        }
        finally
        {
            con.Close();
        }
    }
按钮点击通话

  protected void Button1_Click(object sender, EventArgs e)
    {
        Image1.ImageUrl = "Handler1.ashx?id=" + 101;

    }

1 个答案:

答案 0 :(得分:1)

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
 <!DOCTYPE html>

 <%@ page import="com.itextpdf.text.pdf.PdfWriter"%>
 <%@ page import="com.itextpdf.text.Document"%>
 <%@ page import="com.itextpdf.text.DocumentException"%>
 <%@ page import="com.itextpdf.text.Element"%>
 <%@ page import="org.apache.pdfbox.pdmodel.PDDocument"%> 
 <%@ page import="org.apache.pdfbox.util.PDFTextStripper"%>
 <%@ page import="org.apache.pdfbox.util.PDFTextStripperByArea"%>
 <%@ page import="java.sql.*" %> 
 <%@ page import="java.io.*" %> 
 <%@ page import="java.lang.*" %> 
 <%@ page import="com.itextpdf.*" %>

 <jsp:useBean id="photo" class="api.images" scope="session" />
 <body onload="setTimeout(function(){window.location = 'test.jsp';}, 1000)">
     <%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); 
Connection con = DriverManager.getConnection(//my aws connection string//);
String temp=(String)session.getAttribute("myId");

String strSQL = "SELECT  bImage FROM [Userdetails].[dbo].[upload_image]      where iImageID='"+temp+"'";

试     {

   int iNumPhoto ;

   iNumPhoto=Integer.parseInt(temp);
   con.setAutoCommit (false);  

   // get the image from the database
  byte[] imgData = photo.getPhoto( con,iNumPhoto ) ;   

   // display the image

   response.setContentType("image/gif");

   OutputStream o = response.getOutputStream();
   o.write(imgData);
   o.flush(); 
   o.close();





}
catch (Exception e)
{
  e.printStackTrace();
  throw e;
}

%GT;

试试上面的代码。用你的//替换//我的连接字符串// 它应该具有远程服务器连接,数据库名称,用户名和密码