What is the Most simple way to store image in Data base in MVC - wordpress

ok, So criticism apart, I'm New to MVC, my Point is how can i store an image in data base that will be uploaded by user.
i'm Creating a simple blog via MVC And what i Want is A form Same like WordPress "ADD NEW POST". Where user can enter title,TAGS,Headings, But What my Part is, I have to store all of them in DB. i can Do the CSS part, but i'm struck in Functionality that will be Getting all values From user (view) And Then Storing it in database also Displaying it.
below is my google-d Code for View in MVC.
#model SimpleBlogg.Models.PostContent
#{
ViewBag.Title = "AddContentToDB";
}
<div class="UploadPicForm" style="margin-top:20px;">
#using (Html.BeginForm("AddContentToDB", "AddNewPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}
</div>

Save as Base64 string:
static string base64String = null;
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
public System.Drawing.Image Base64ToImage()
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
protected void ImageToBase_Click(object sender, EventArgs e)
{
TextBox1.Text = ImageToBase64();
}
protected void BaseToImage_Click(object sender, EventArgs e)
{
Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));
Image1.ImageUrl = "~/Images/Hello.jpg";
}
source: http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64-string-to-image

Related

How to get image from Image control and save into local directory as jpeg image in asp.net?

i am loading image from asp.net handler as below> handler fetches image using web service. Handler returns as bytes[] data.
<asp:Image ID="image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>
Now, I have image in the web page. I have save Image button in the web page. When button clicked, I want to save this image into local directory (c:\images) as a jpeg image. How to achieve this?
Try to use the following code for handler, which returns image data:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
bool isSave = !String.IsNullOrEmpty(context.Request["save"]);
int imgId;
if (String.IsNullOrEmpty(context.Request["id"]) || Int32.TryParse(context.Request["id"], out imgId))
throw new ArgumentException("No parameter specified");
byte[] imageData = LoadImageFromWebService(imgId); //load image from web service
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader("Content-Length", imageData.Length.ToString());
context.Response.AddHeader("Content-Disposition", String.Format("{0} filename=image.jpeg", isSave ? "attachment;" : String.Empty));
context.Response.BinaryWrite(imageData);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Change asp.net page as follows:
<asp:Image ID="Image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>
<asp:ImageButton ID="ImageButton1" OnClick="OnImageClick" runat="server" />
In this case your OnImageClick handler in page will be:
protected void OnImageClick(object sender, ImageClickEventArgs e)
{
Response.Redirect("~/Handler1.ashx?id=1&save=1");
}
I think that you must get the path of the image control
inside the click event
as
string path = image1.ImageUrl;
and then save it to the file
hope this helps you
public class ImageHandler : IHttpHandler
{
Users objimage = new Users();
public void ProcessRequest(HttpContext context)
{
Int32 theID;
if (context.Request.QueryString["Id"] != null)
theID = Convert.ToInt32(context.Request.QueryString["Id"]);
else
throw new ArgumentException("No parameter specified");
HttpResponse r = context.Response;
r.ContentType = "image/jpeg";
context.Response.ContentType = "image/jpeg";
objimage.imageId = theID; //select image using id
Stream strm = objimage.SelectImageByID(theID);
byte[] buffer = new byte[2048];
if (strm != null)
{
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
else
{
r.WriteFile("~/img/img-profile.jpg");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

How to pass image to Eval method from handler.ashx to imageurl?

I want to retrieve image from database and display in an aspx page. I use Linq to SQL. And a Generic handler.
Handler2.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
int id;
string sid = context.Request.QueryString["id"];
if (int.TryParse(sid, out id))
{
Stream strm = getImage(id);
byte[] buffer = new byte[4096];
int i = strm.Read(buffer, 0, 4096);
while (i > 0)
{
context.Response.OutputStream.Write(buffer, 0, 4096);
i = strm.Read(buffer, 0, 4096);
}
}
else
{
//
}
}
}
public Stream getImage(int id)
{
using (DummyDBEntities cntx = new DummyDBEntities())
{
var db = from c in cntx.Images
where c.imageId == id
select c.imageData;
MemoryStream ms = new MemoryStream();
byte[] byteArray = new byte[db.ToArray().Length];
ms.Write(byteArray, 0, db.ToArray().Length);
return new MemoryStream(byteArray);
}
}
And a button control in Default.aspx page when I click, redirects to handler1.ashx. Gets the id of image from database and supposed to Show it in Default.aspx asp:image control
protected void btnGetID_Click(object sender, EventArgs e)
{
int id=Convert.ToInt32(txtGetID.Text);
Response.Redirect("Handler2.ashx?id="+id);
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
}
How do i supposed to write Eval method and the querystring to pass the image to imageurl?
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
Please help, thanks.
I hope I understood your problem right.
You want to display the image from your handler in the Image1. For that you can just do the following
Image1.ImageUrl = ResolveUrl("~/Handler2.ashx?id=" + id);

Compressing viewstate is adding another hidden field with same id as __VIEWSTATE

I am trying to compress viewstate in ASP.Net 4.0, so the page loads more quickly for heavily bloated viewstate pages.
However, when I view source of page in browser, I am finding 2 hidden fields with same name and id of '__VIEWSTATE'.
My code is as below. How can I compress the view state but let it be stored in its original hidden field without creating another duplicate hidden field?
protected override void SavePageStateToPersistenceMedium(object viewState)
{
byte[] viewStateArray;
using (MemoryStream memoryStream = new MemoryStream())
{
_objectStateFormatter.Serialize(memoryStream, viewState);
viewStateArray = memoryStream.ToArray();
}
ClientScript.RegisterHiddenField("__VIEWSTATE",
Convert.ToBase64String(GZip.Compress(viewStateArray)));
}
using System.IO;
using System.IO.Compression;
using System.Web.UI;
public class PageCompressed : System.Web.UI.Page
{
private ObjectStateFormatter _formatter = new ObjectStateFormatter();
protected override void SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
_formatter.Serialize(ms, viewState);
byte[] viewStateArray = ms.ToArray();
ClientScript.RegisterHiddenField("__CVIEWSTATE", Convert.ToBase64String(_Compress(viewStateArray)));
}
protected override object LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__CVIEWSTATE"];
byte[] bytes = Convert.FromBase64String(vsString);
bytes = _DeCompress(bytes);
return _formatter.Deserialize(Convert.ToBase64String(bytes));
}
private byte[] _Compress(byte[] inputBytes)
{
MemoryStream m = new MemoryStream();
GZipStream zip = new GZipStream(m, CompressionMode.Compress, true);
zip.Write(inputBytes, 0, inputBytes.Length);
zip.Close();
return m.ToArray();
}
private byte[] _DeCompress(byte[] inputBytes)
{
MemoryStream m = new MemoryStream(inputBytes);
MemoryStream mout = new MemoryStream();
GZipStream zip = new GZipStream(m, CompressionMode.Decompress, true);
do
{
byte[] bBuffer = new byte[4097];
int iRead = zip.Read(bBuffer, 0, bBuffer.Length);
if (iRead > 0)
{
mout.Write(bBuffer, 0, iRead);
}
else
{
break;
}
} while (true);
zip.Close();
return mout.ToArray();
}
}
you can use this Interface Class to compress viewstate by inheriting from it like this in code behind for every page
public partial class Default : PageCompressed

How to use Using the HtmlAgilityPack to get table value

http://www.dsebd.org/latest_PE_all2_08.php
i work on asp.net C# web.Above url contain some information ,i need to save them in my database and also need to save then in specified location as xml format.This url contain a table.I want to get this table value but how to retrieve value from this html table.
HtmlWeb htmlWeb = new HtmlWeb();
// Creates an HtmlDocument object from an URL
HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("http://www.dsebd.org/latest_PE_all2_08.php");
I need help to get table information from this document .How to save this table value.Show me some syntax
public partial class WebForm3 : System.Web.UI.Page
{
private byte[] aRequestHTML;
private string myString = null;
protected System.Web.UI.WebControls.Label Label1;
private ArrayList a = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
WebClient objWebClient = new WebClient();
aRequestHTML = objWebClient.DownloadData("http://www.dsebd.org/latest_PE_all2_08.php");
// creates UTf8 encoding object
UTF8Encoding utf8 = new UTF8Encoding();
// gets the UTF8 encoding of all the html we got in aRequestHTML
myString = utf8.GetString(aRequestHTML);
string html = #"
<html><head></head>
<body><div>
<table border=1>
<tr><td>sno</td><td>sname</td></tr>
<tr><td>111</td><td>abcde</td></tr>
<tr><td>213</td><td>ejkll</td></tr>
</table>
<table border=1>
<tr><td>adress</td><td>phoneno</td><td>note</td></tr>
<tr><td>asdlkj</td><td>121510</td><td>none</td></tr>
<tr><td>asdlkj</td><td>214545</td><td>none</td></tr>
</table>
</div></body>
</html>";
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(myString);
DataTable addressAndPhones;
foreach (var table in ParseAllTables(htmlDoc))
{
if (table.Columns.Contains("Trading Code") && table.Columns.Contains("Close Price"))
{
// You found the address and phone number table
addressAndPhones = table;
}
}
}
private static DataTable[] ParseAllTables(HtmlDocument doc)
{
var result = new List<DataTable>();
foreach (var table in doc.DocumentNode.Descendants("table"))
{
result.Add(ParseTable(table));
}
return result.ToArray();
}
private static DataTable ParseTable(HtmlNode table)
{
var result = new DataTable();
var rows = table.Descendants("tr");
var header = rows.Take(1).First();
foreach (var column in header.Descendants("td"))
{
result.Columns.Add(new DataColumn(column.InnerText, typeof(string)));
}
foreach (var row in rows.Skip(1))
{
var data = new List<string>();
foreach (var column in row.Descendants("td"))
{
data.Add(column.InnerText);
}
result.Rows.Add(data.ToArray());
}
return result;
}
}
In this way u can easily create a DataTable and then can save is DataBase.

image management code?

two days back i ask a question for image management, i get some reference that is 4guys
the code is working fine i want to store that manged image in a folder but i not understand how can i save, can u help me. this is my code.....
public partial class Default2 : System.Web.UI.Page
{
public bool ThumbnailCallback()
{
return false;
}
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = default(System.Drawing.Image.GetThumbnailImageAbort);
dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image fullSizeImg = default(System.Drawing.Image);
fullSizeImg = System.Drawing.Image.FromFile("C:\\05.jpg");
System.Drawing.Image thumbNailImg = default(System.Drawing.Image);
thumbNailImg = fullSizeImg.GetThumbnailImage(100, 100, dummyCallBack, IntPtr.Zero);
}
}
To save an image to a folder on the server, call image.Save(path).
EDIT: You can send a smaller version of an image to the browser like this:
using(Image originalImage = something)
using(Bitmap smallImage = new Bitmap(originalImage, width, height)) {
Stream stream = new MemoryStream();
smallImage.Save(stream);
Response.OutputStream.Write(stream.ToArray(), 0, stream.Length);
}

Resources