This is my table in database :
And I read the database like :
DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
So, thisuser.picture is a handle to the image. But how can I show it in asp:image control on my page ?
Edit
I save the picture with this code :
DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.First(p => p.username == User.Identity.Name);
byte[] filebyte = FileUpload1.FileBytes;
System.Data.Linq.Binary fileBinary = new System.Data.Linq.Binary(filebyte);
thisuser.picture = fileBinary;
db.SubmitChanges();
is there something wrong ?
The ASP.NET Image control loosely represents an <img> tag in HTML. As a result you can only get an image into an HTML doocument by setting the URL to the image content you want to embed in the page.
<img src="images/picture.png" />
This means that you need a mechanism to take an HTTP request asking for an image resource, and return a response containing the image binary data.
With ASP.NET Web API this becomes a trivial operation to implement:
public HttpResponseMessage GetImage(string username)
{
DataClassesDataContext db = new DataClassesDataContext();
usertable thisuser = db.usertables.FirstOrDefault(
p => p.username == username);
if (thisuser == null)
{
return new HttpResponseMessage(HttpStatusCode.NotFound));
}
// Create a stream to return to the user.
var stream = new MemoryStream(thisuser.picture.ToArray());
// Compose a response containing the image and return to the user.
var result = new HttpResponseMessage();
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("image/jpeg");
return result;
}
If you can't use Web API, you'll have to implement an HTTP Handler to do the same job.
In your ASP.NET page, you will have to set the property ImageUrl to the address configured for your controller/handler, including the username as part of the URL.
<asp:Image ImageUrl='<%# GetImage(Eval("IMG_DATA")) %>' />
Above we tell the ASPX engine that we want to take value of column [IMG_DATA], and pass it into method GetImage of the page, which should return a valid image. So, let's implement the method inside our page class:
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
You'll need to create generic handler - lets call it ImageHandler.ashx, and it will be in the root of your web app.
public class ImageHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
// here is the tricky part - you don't store image type anywhere (you should)
// assuming jpeg
context.Response.ContentType = "image/jpeg";
DataClassesDataContext db = new DataClassesDataContext();
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity != null) {
var thisuser = db.usertables.First(p => p.username == HttpContext.Current.User.Identity.Name);
if (thisuser != null) {
byte[] buffer = thisuser.picture.ToArray();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
}
public bool IsReusable {
get { return false; }
}
}
Then in the page, add:
<asp:Image runat="server" ImageUrl="~/ImageHandler.ashx" />
Few notes:
you should consider caching of the image
you should switch from image sql type to varbinary (http://msdn.microsoft.com/en-us/library/ms187993.aspx)
you should store image mimetype somewhere (if it is jpeg, png, bmp) - preferably in the same table, and server the correct mimetype in the handler
-
if thisuser.picture has a proper path to your image, you can try something like this:
Image im = new Image();
im.ID = "myImg";
im.ImageUrl = thisuser.picture.toString();
this.Controls.Add(im);
I am assuming that you are using web forms (I don't think it makes a difference).
Also, this might require a page refresh. The 'this' is referring to the Page object (in my case).
You can't render it directly using the ASP.NET Image control (or at least not that I'm immediately aware of). Quickly of the top of my head:
Solution 1:
You need some HttpHandler for your images. In your asp:image tag you need an ImageUrl that will be picked up by this specific HttpHandler. There you can write out the image content from the database as bytes using the right MIME type and headers.
Solution 2:
Take a look into embedding data in URLs, perhaps you can write out your image like this and add it to the asp:image ImageUrl like that: https://en.wikipedia.org/wiki/Data_URI_scheme
create ashx page. On it use somthing like this
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Stream strm = new MemoryStream(GetImage(ID));
long length = strm.Length;
byte[] buffer = new byte[length];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
ON get image method
public static byte[] GetImage(string ImageId)
{
byte[] img = null;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_SELECT_GLOBAL_METHOD";
cmd.Parameters.AddWithValue("#EVENT", 5);
cmd.Parameters.AddWithValue("#CODE", ImageId);
cmd.Connection = DL_CCommon.Connection();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
img = (byte[])dr[0];
}
dr.Close();
return img;
}
this method return returns the image as ur ID.
on your aspx page..
Image1.ImageUrl = "somthing.ashx?ID="+userImageID;
I hope it will work. as i have found it worked in my own. Thank you
Related
I have to get all the videos from a youtube channel. I have used following code but it is returning only top 25 videos. I need all the uploaded videos. Please help me regarding this.
public class YoutubeVideoHelper
{
const string YOUTUBE_CHANNEL = "UPGovtOfficial";
const string YOUTUBE_DEVELOPER_KEY = "My Developer key";
public static DataTable GetVideos()
{
DataTable dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("VideoId");
YouTubeRequestSettings settings =
new YouTubeRequestSettings(YOUTUBE_CHANNEL, YOUTUBE_DEVELOPER_KEY);
YouTubeRequest request = new YouTubeRequest(settings);
string feedUrl = String.Format
("http://gdata.youtube.com/feeds/api/users/{0}/uploads?orderby=published&max-result=100",
YOUTUBE_CHANNEL);
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (var video in videoFeed.Entries)
{
DataRow dr = dt.NewRow();
dr["Title"] = video.Title;
dr["VideoId"] = video.VideoId;
dt.Rows.Add(dr);
}
return dt;
}
}
Try this:
Set AutoPaging to true and specify Maximum,PageSize properties values to required value (100) of YouTubeRequestSettings object.
Below is the link for more details:
http://google-gdata.googlecode.com/svn-history/r890/docs/folder54/AllMembers_T_Google_GData_Client_RequestSettings.htm
I had my code to retrieve logged user details , every thing is OK but
i cannot retrieve the user image .
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", Environment.UserName);
//SearchResult findUser = searcher.FindOne();
foreach (SearchResult findUser in searcher.FindAll())
{
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
string userName = user.Properties["displayName"].Value.ToString();
string departement = user.Properties["Department"].Value.ToString();
string title = user.Properties["title"].Value.ToString();
string[] rt = new string[] { Login, userName, Email, Mobile };
Lbl_User.Text = userName;
Lbl_Administrative.Text = departement;
Lbl_Position.Text = title;
}
}
I've just taken your code and made a method out of it just to retrieve the image. You would need to refactor it, to either get only the byte[] or thw whole image.
//add this
using System.Drawing;
static Image GetPhotoFromAD(string userName)
{
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.Subtree;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", userName);
//SearchResult findUser = searcher.FindOne();
foreach (SearchResult findUser in searcher.FindAll())
{
if (findUser != null)
{
byte[] photodata = findUser.Properties["jpegPhoto"].Value as byte[];
using (MemoryStream str = new MemoryStream(photodata))
{
return Bitmap.FromStream(str);
}
}
}
}
If you only want the raw data, the important bit is byte[] photodata = user.Properties["jpegPhoto"].Value as byte[];
The binary image should be stored in property called thumbnailPhoto.
var photo = user.Properties["thumbnailPhoto"];
if (photo != null) {
byte[] buffer = (byte[])photo.Value;
//var bitmap = new Bitmap(new MemoryStream(buffer, false));
//bitmap.Save(#"c:\test.bmp");
}
Now, given the fact that you tagged question as asp.net you'll have to write generic handler (.ashx) for retrieving the image. This handler should write content of
photo.Value
into response output stream and set content type to image/bmp
In your control/page just reference the handler like
<img src="/GenericHandler.ashx" alt="My image" />
I'm using this tutorial https://web.archive.org/web/20211020001747/https://www.4guysfromrolla.com/articles/030211-1.aspx that’s uses a PDF template, lets the user input fields using textbox's. The file downloads onto the client’s pc but I would like to save a copy of the file into a sql database also or just save the file in the database instead of both.
protected void btnGeneratePDF_Click(object sender, EventArgs e)
{
var pdfPath = Path.Combine(Server.MapPath("~/PDFTemplates/fw9.pdf"));
// Get the form fields for this PDF and fill them in!
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
formFieldMap["topmostSubform[0].Page1[0].f1_01_0_[0]"] = txtName.Text;
formFieldMap["topmostSubform[0].Page1[0].f1_02_0_[0]"] = txtBusinessName.Text;
if (rblTaxClassification.SelectedValue != null)
{
var formFieldName = string.Format("topmostSubform[0].Page1[0].c1_01[{0}]", rblTaxClassification.SelectedIndex);
formFieldMap[formFieldName] = (rblTaxClassification.SelectedIndex + 1).ToString();
}
if (chkExemptPayee.Checked)
formFieldMap["topmostSubform[0].Page1[0].c1_01[7]"] = "8";
formFieldMap["topmostSubform[0].Page1[0].f1_04_0_[0]"] = txtAddress.Text;
formFieldMap["topmostSubform[0].Page1[0].f1_05_0_[0]"] = txtCityStateZIP.Text;
formFieldMap["topmostSubform[0].Page1[0].f1_07_0_[0]"] = txtAccountNumbers.Text;
// Requester's name and address (hard-coded)
formFieldMap["topmostSubform[0].Page1[0].f1_06_0_[0]"] = "Acme Website\n123 Anywhere Lane\nSpringfield, USA";
// SSN
if (!string.IsNullOrEmpty(txtSSN1.Text))
{
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField1[0]"] = txtSSN1.Text;
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[0]"] = txtSSN2.Text;
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[1]"] = txtSSN3.Text;
}
else if (!string.IsNullOrEmpty(txtEIN1.Text))
{
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[2]"] = txtEIN1.Text;
formFieldMap["topmostSubform[0].Page1[0].social[0].TextField2[3]"] = txtEIN2.Text;
}
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
PDFHelper.ReturnPDF(pdfContents, "Completed-W9.pdf");
FileStream fs = new FileStream(pdfPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = "Completed-W9132.pdf";
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "application/pdf";
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
App_code/pdfHelper.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
// See http://stackoverflow.com/questions/4491156/get-the-export-value-of-a-checkbox-using-itextsharp/
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
// /D is for the "down" appearances.
// if there are normal appearances, one key will be "Off", and the other
// will be the export value... there should only be two.
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/', so remove it!
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
}
The parts of the tutorial you're looking for in that case are right here:
Response.ContentType = "application/pdf";
Response.BinaryWrite(output.ToArray());
When saving a "file" to a database you essentially care about two (maybe three) things:
The byte array of the file contents
The type of the file
(Maybe a name for the file)
Since the tutorial concludes with two of these things (above), the type and the data, you can store these two things into your database however you need to store them. This depends on the database you're using, how you access that database, etc. Essentially to store these two things you just need a text column (varchar?) and a binary (or "blob") column (varbinary?).
The only difference is that instead of setting the type as a header in an HTTP response and writing the bytes to that HTTP response, you're using both of them as values in your database. Everything else is the same.
I am trying to write a httphandler to retrieve image url and later display it on a image control i am using this code but its not working
OleDbConnection mDB = new OleDbConnection(
ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString);
mDB.Open();
OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB);
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
context.Response.BinaryWrite((byte[])rdr[0]);
mDB.Close();
context.Response.End(); */
sorry that i caused a confusion earlier in the SELECT statement the pProductId does not contain the URL of the image instead pProductImage is the field that contain the URL. i am using the Id to identify which image to display accordingly.
this is my expected output:
<img src="ImgHandler.ashx?pProductId=2" alt="" />
i cant place image this is the link to my error msg:http://imgur.com/Cix67
This is a two steps answer.
In the page, you can do something like this:
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
using (OleDbCommand cmd = new OleDbCommand("select pProductId from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.Write("<img src=\"ImgHandler.ashx?pProductId=");
context.Response.Write((int)rdr[0]); // I suppose pProductId is an int, adapt accordingly
context.Response.Write("\" />");
}
}
}
and in the HTTP handler implicitly triggered, something like this:
public class MyHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
using (OleDbConnection mDB = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnection"].ConnectionString))
{
mDB.Open();
// select the file data (I put pData here as a placeholder, and assume it will be a byte[])
using (OleDbCommand cmd = new OleDbCommand("select pData from Products where pProductId=" + context.Request.QueryString["ImageID"], mDB))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
context.Response.ContentType = "image/png";// put the content type here
context.Response.BinaryWrite((byte[])rdr[0]);
}
}
}
}
}
Note the using pattern which ensures proper resources cleanup once used. Also, ideally you could cache the data on the client using proper cache HTTP headers (like if-modified-since) but this is another story ...
How to an image which is retrieved from MYSQL database.
To display a text in textbox we use textbox.TEXT --> We use .TEXT to display text
Likewise how to display an Image retrieved from MYSQL database??
Image1.[___] = dr[0].[_____];
What to be filled in the above blanks??...
I used blob to store image.
You can do it by creating a controller to serve up your image like and then in your view you can just add the call inline:
<img src='<%= Url.Action( "GetImage", "Image", new { id = yourImageIdHere } ) %>' />
public class ImageController
{
public ActionResult GetImage(int id)
{
var image = GetTheRawBinaryImageFromTheDB();
return File(image, "image/jpg" );
}
}
Add a Generic Handler to your Web Forms application and in the ProcessRequest method, you need to query the database for the relevant file/binary data. You would pick the right image via a querystring, usually. The following code shows how you can query the database and return the binary data:
using (DbConnection conn = new DbConnection(connect))
{
if (context.Request.QueryString["id"] != null)
{
DbCommand cmd = new DbCommand(qry, conn);
cmd.Parameters.AddWithValue("", context.Request.QueryString["id"]);
conn.Open();
using (DbDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read();
context.Response.AddHeader("content-disposition", "attachment; filename=" + rdr["FileName"]);
context.Response.ContentType = rdr["MimeType"].ToString();
context.Response.BinaryWrite((byte[])rdr["Blob"]);
}
}
}
}
You need to change the DbConnection, DbCommand and DbDataReader to the type that your provider likes (Odbc or MySql) and then point the ImageUrl property of your Image control to the HttpHandler:
Image1.ImageUrl = "MyHandler.ashx?id=" + whatever the image id is.