i want to rotate the image stored inside the database is this possible ?
i can get the image from the database i just don't know how to rotate it.
string img = (Request.QueryString["cn"]);
Byte[] bytes = null;
if (rbPhoto1.Checked == true)
{
if (img != null)
{
//string str = "select mem_contenttype, mem_photo from tblCardRequestDetail2 where mem_cardno = '" + Request.QueryString["cn"] + "'";
string str = "select mem_contenttype1, mem_photo1 from tblphotoupload where mem_cardno = '" + img + "'";
SqlCommand cmd = new SqlCommand(str); cmd.Parameters.Add("#1", SqlDbType.VarChar).Value = img;
DataTable dt = GetData(cmd);
bytes = (Byte[])dt.Rows[0]["mem_photo1"];
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["mem_contenttype1"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["mem_photo1"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
//Response.End();
}
}
You can try below code
var memStream = new MemoryStream(bytes);
Image imgFromStream = Image.FromStream(memStream, true);
imgFromStream.RotateFlip(RotateFlipType.Rotate90FlipNone);
imgFromStream.Save(memStream,System.Drawing.Imaging.ImageFormat.Jpeg);//Change to whichever format you need
bytes = imgFromStream.ToArray();
You can use a helper method like this:
public static byte[] ReadRotateAndWriteBitmap(byte[] imageBytes)
{
ImageConverter converter = new ImageConverter();
using (Image img = (Image)converter.ConvertFrom(imageBytes))
{
if (img == null)
return null;
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
}
Related
First and foremost, I apologize for my grammatical errors; my first language is Persian (Iran).
I use the following code to insert the image and retrieve it from the Access database, and I have no problem retrieving it after inserting the image.
BitmapImage BM;
private void UploadButton_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
System.Windows.Forms.OpenFileDialog OpenFileDialog = new System.Windows.Forms.OpenFileDialog();
OpenFileDialog.AutoUpgradeEnabled = false;
if (App.EnumLanguage.Equals(AllLanguage.English))
{
OpenFileDialog.Title = "Selecting Image";
}
else
{
OpenFileDialog.Title = "انتخاب تصویر";
}
OpenFileDialog.Filter = "JPG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp|GIF(*.gif)|*.gif|PNG(*.png)|*.png|All Files|*.*";
if (OpenFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var IMG = System.Drawing.Image.FromFile(OpenFileDialog.FileName);
BM = new BitmapImage(new Uri(OpenFileDialog.FileName));
BitmapImage BitMapImage = new BitmapImage();
BitMapImage.BeginInit();
System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream();
IMG.Save(MemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
MemoryStream.Seek(0, System.IO.SeekOrigin.Begin);
BitMapImage.StreamSource = MemoryStream;
BitMapImage.EndInit();
BookImage.Source = BitMapImage;
OpenFileDialog.Dispose();
}
}
private static byte[] ImageToBytes(BitmapImage image)
{
byte[] Data;
JpegBitmapEncoder JpegEncoder = new JpegBitmapEncoder();
JpegEncoder.Frames.Add(BitmapFrame.Create(image));
using (System.IO.MemoryStream MS = new System.IO.MemoryStream())
{
JpegEncoder.Save(MS);
Data = MS.ToArray();
}
return Data;
}
private BitmapImage GetImageFromBytes(byte[] bytes)
{
System.IO.MemoryStream Stream = new System.IO.MemoryStream();
Stream.Write(bytes, 0, bytes.Length);
Stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(Stream);
BitmapImage bitImage = new BitmapImage();
bitImage.BeginInit();
System.IO.MemoryStream MS = new System.IO.MemoryStream();
img.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
MS.Seek(0, System.IO.SeekOrigin.Begin);
bitImage.StreamSource = MS;
bitImage.EndInit();
return bitImage;
}
private void Add_Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
OleDbConnect.Open();
if (BM != null)
{
byte[] Image_Bytes = ImageToBytes(BM);
OleDbParameter Parameter = new OleDbParameter();
Parameter.OleDbType = OleDbType.Binary;
Parameter.ParameterName = "Image";
Parameter.Value = Image_Bytes;
OleDbCommand OleDbCommand_Insert = new OleDbCommand("Insert Into [BookTable](BookName,Publisher,Category,IDNumber,Status,HistoryTaken,RecipientName,ReturnDate,BookImage)values('" + BookName_TextBox.Text + "','" + Publisher_TextBox.Text + "','" + Category_ComboBox.Text + "','" + IDNumber_TextBox.Text + "','" + Status_ComboBox.Text + "','" + HistoryTaken_TextBox.Text + "','" + RecipientName_TextBox.Text + "','" + ReturnDate_TextBox.Text + "',#Image)", OleDbConnect);
OleDbCommand_Insert.Parameters.Add(Parameter);
OleDbCommand_Insert.ExecuteScalar();
}
OleDbConnect.Close();
}
\\\ retrieving information from Access Database
OleDbCommand OleDCmd = new OleDbCommand("Select * From BookTable Where IDNumber='" + Search_ComboBox.Text.Trim() + "'", OleDbConnect);
OleDCmd.CommandType = System.Data.CommandType.Text;
OleDbConnect.Open();
OleDbDataReader DataReader = OleDCmd.ExecuteReader();
while (DataReader.Read())
{
BookName_TextBox.Text = DataReader[0].ToString();
Publisher_TextBox.Text = DataReader[1].ToString();
Category_ComboBox.Text = DataReader[2].ToString();
IDNumber_TextBox.Text = DataReader[3].ToString();
Status_ComboBox.Text = DataReader[4].ToString();
HistoryTaken_TextBox.Text = DataReader[5].ToString();
RecipientName_TextBox.Text = DataReader[6].ToString();
ReturnDate_TextBox.Text = DataReader[7].ToString();
BitmapImage BMP = GetImageFromBytes((byte[])DataReader[8]);
BookImage.Source = BMP;
}
But when I use the following commands to update the image and other information, this error is displayed when I want to retrieve the information.
byte[] Image_Bytes = ImageToBytes(BM);
OleDbParameter Parameter = new OleDbParameter();
Parameter.OleDbType = OleDbType.Binary;
Parameter.ParameterName = "Image";
Parameter.Value = Image_Bytes;
OleDbCommand OleDbCommand_Update = new OleDbCommand("Update [BookTable] Set BookName='"+BookName_TextBox.Text.Trim()+"',Publisher='"+Publisher_TextBox.Text.Trim()+"',Category='"+Category_ComboBox.Text.Trim()+"',Status='"+Status_ComboBox.Text.Trim()+"',HistoryTaken='"+HistoryTaken_TextBox.Text.Trim()+"',RecipientName='"+RecipientName_TextBox.Text.Trim()+"',ReturnDate='"+ReturnDate_TextBox.Text.Trim() +"',BookImage='"+ "#Image" + "'Where IDNumber='" + IDNumber_TextBox.Text.Trim()+ "'", OleDbConnect);
OleDbCommand_Update.Parameters.Add(Parameter);
OleDbCommand_Update.ExecuteScalar();
System.ArgumentException: 'Parameter is not valid.'
Line 6 gives an error
private BitmapImage GetImageFromBytes(byte[] bytes)
{
System.IO.MemoryStream Stream = new System.IO.MemoryStream();
Stream.Write(bytes, 0, bytes.Length);
Stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(Stream);\\System.ArgumentException: 'Parameter is not valid.'
BitmapImage bitImage = new BitmapImage();
bitImage.BeginInit();
System.IO.MemoryStream MS = new System.IO.MemoryStream();
img.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
MS.Seek(0, System.IO.SeekOrigin.Begin);
bitImage.StreamSource = MS;
bitImage.EndInit();
return bitImage;
}
In short:in insert command i have no problem to retrieve image but in update command i have problem to retrieve image.
In my opinion, the Update command does not save the image properly in the Access database.
Thanks
Hooray, hooray I found the solution (I found it myself).if IDNumber data type as be number data type in Access Database , this code works 100%.
Just Replace this code...
OleDbCommand OleDbCommand_Update = new OleDbCommand("Update [BookTable] Set BookName='"+BookName_TextBox.Text.Trim()+"',Publisher='"+Publisher_TextBox.Text.Trim()+"',Category='"+Category_ComboBox.Text.Trim()+"',Status='"+Status_ComboBox.Text.Trim()+"',HistoryTaken='"+HistoryTaken_TextBox.Text.Trim()+"',RecipientName='"+RecipientName_TextBox.Text.Trim()+"',ReturnDate='"+ReturnDate_TextBox.Text.Trim() +"',BookImage='"+ "#Image" + "'Where IDNumber='" + IDNumber_TextBox.Text.Trim()+ "'", OleDbConnect);
With the following code (this is how the UPDATE Query command should be written)
OleDbCommand OleDbCommand_Update = new OleDbCommand("Update [BookTable] Set BookImage=Image,BookName='" +BookWindow.BookName_TextBox.Text.Trim() + "',Publisher='" + BookWindow.Publisher_TextBox.Text.Trim() + "',Category='" + BookWindow.Category_ComboBox.Text.Trim() + "',Status='" + BookWindow.Status_ComboBox.Text.Trim() + "',HistoryTaken='" + BookWindow.HistoryTaken_TextBox.Text.Trim() + "',RecipientName='" + BookWindow.RecipientName_TextBox.Text.Trim() + "',ReturnDate='" + BookWindow.ReturnDate_TextBox.Text.Trim() + "'Where IDNumber=" + BookWindow.IDNumber_TextBox.Text.Trim(), OleDbConnect);
I tested a lot until I finally got the result.
Thanks a lot for your help.
imagehandler.ashx image doesn't display in Chrome browser. How can I fix it..?
My Codes (imagehandler.ashx):
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["YazarID"] != null)
{
string YazarID = context.Request.QueryString["YazarID"];
DataTable dt = new DataTable();
string query = "select img from Register where YazarID='" + YazarID + "'";
dt = Database.GetData(query);
HttpResponse r = context.Response;
r.WriteFile("../Pictures/300/" + dt.Rows[0]["img"]);
HttpContext.Current.ApplicationInstance.CompleteRequest();
context.Response.Flush();
context.Response.Close();
context.Response.End();
}
}
images looking like this in Chrome browser;
You are not sending the content-Length. It could mess up the images (and other files) in Chrome. Assuming the file is correctly saved in the database of course.
public void ProcessRequest(HttpContext context)
{
//create a new byte array
byte[] bin = new byte[0];
//get the item from a datatable
bin = (byte[])dt.Rows[0]["img"];
//read the image in an `Image` and then get the bytes in a memorystream
Image img = Image.FromFile(context.Server.MapPath("test.jpg"));
using (var ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bin = ms.ToArray();
}
//or as one-liner
bin = File.ReadAllBytes(context.Server.MapPath("test.jpg"));
//clear the buffer stream
context.Response.ClearHeaders();
context.Response.Clear();
context.Response.Buffer = true;
//set the correct ContentType
context.Response.ContentType = "image/jpeg";
//set the filename for the image
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"myImage.jpg\"");
//set the correct length of the string being send
context.Response.AddHeader("content-Length", bin.Length.ToString());
//send the byte array to the browser
context.Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
context.Response.Flush();
context.ApplicationInstance.CompleteRequest();
}
I wrote some code for making PDF from HTML with pechkin and pechkin.synchronized.
It will work very well at first time.
Since second time, images are disappeared in pdf.
Other [html to pdf]s are too. First pdf is right. Other pdfs are not.
At the first time in server, it will work.
Maybe because pechkin will not unload in memory. I think.
I need help.
System.IO.File.WriteAllText(textfilepath, html);
GlobalConfig gc = new GlobalConfig();
ObjectConfig oc = new ObjectConfig()
.SetLoadImages(true)
.SetZoomFactor(1.0)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true)
.SetAllowLocalContent(true)
.SetPageUri(url);
IPechkin pechkin = new Pechkin.Synchronized.SynchronizedPechkin(gc);
pdf = pechkin.Convert(oc);
using NReco.ImageGenerator;
using NReco.PdfGenerator;
//아래 주석들을 잘 여닫으면 jpg로 저장할 수 있다.
/*
'C:\inetpub\wwwroot\...\bin\wkhtmltopdf.exe' 경로에 대한 액세스가 거부되었습니다.
'C:\inetpub\wwwroot\...\bin\msvcp120.dll' 경로에 대한 액세스가 거부되었습니다.
'C:\inetpub\wwwroot\...\bin\msvcr120.dll' 경로에 대한 액세스가 거부되었습니다.
위 세 파일을 해당 경로에 넣어 주면 정상 작동한다.
*/
string article_no = Request["article_no"];
//string[] urlArray = Request["url"].Split('/');
//string textfilename = Guid.NewGuid().ToString() + ".html";
//string url = urlArray[0] + "//" + urlArray[2] + "/storage/print/" + textfilename;
//string textfilepath = Server.MapPath("/storage/print/" + textfilename);
string html = "<html>"+HttpUtility.UrlDecode(Request["html"])+"</html>";
//string jpgpath = Server.MapPath("/storage/print/") + article_no + ".jpg";
string pdfpath = Server.MapPath("/storage/print/") + article_no + ".pdf";
try
{
//byte[] jpg;
byte[] pdf;
//if (System.IO.File.Exists(jpgpath))
if (System.IO.File.Exists(pdfpath))
{
//jpg = System.IO.File.ReadAllBytes(jpgpath);
pdf = System.IO.File.ReadAllBytes(pdfpath);
}
else
{
#region Transform the HTML into PDF
//System.IO.File.WriteAllText(textfilepath, html);
//jpg
/*
var htmlToImageConv = new HtmlToImageConverter();
jpg = htmlToImageConv.GenerateImage(html, ImageFormat.Jpeg);
//jpg = htmlToImageConv.GenerateImageFromFile(textfilepath, ImageFormat.Jpeg);
*/
//pdf
var htmlToPdf = new HtmlToPdfConverter();
pdf = htmlToPdf.GeneratePdf(html);
//htmlToPdf.GeneratePdfFromFile(url, null, pdfpath);
System.IO.File.WriteAllBytes(pdfpath, pdf);
//System.IO.File.Delete(textfilepath);
#endregion
}
#region Return the pdf file
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
//Response.AddHeader("Content-Disposition", string.Format("attachment;filename={1}.jpg; size={0}", jpg.Length, article_no));
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={1}.pdf; size={0}", pdf.Length, article_no));
Response.BinaryWrite(pdf);
Response.Flush();
Response.End();
#endregion
I'm saving images into the table using this code:
if (FileUploadControl.PostedFile.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
{
byte[] imagedata = MSImage.ConvertToByte(FileUploadControl);
if (imagedata != null)
{
string param = "#Image";
SqlParameter sp = spc.Add(new SqlParameter(param, SqlDbType.VarBinary, -1));
sp.Value = imagedata;
sql += ", " + Q.C(Database.MSImage) + "=" + param + ", " + Q.C(Database.MSImageType) + "=N'" + FileUploadControl.PostedFile.ContentType + "'";
}
}
And attempting to load it into background-image style with this code:
string imagedata = MSImage.ConvertToImage((byte[])ms[Database.MSImage]);
if (imagedata != null && ms[Database.MSImageType] != DBNull.Value && ((string)ms[Database.MSImageType]).StartsWith("image/", StringComparison.OrdinalIgnoreCase))
{
takzir2.InnerHtml = "<div class='msbgimage' style=\"background-image:url(data:" + (string)ms[Database.MSImageType] + ";base64, " + imagedata + ")\"></div>";
}
The problem is that it won't load the image, and when I try inspecting the element, it gets really stuck because the converted byte array returned a very long string (that sums up in about 650k characters).
This is my MSImage class:
public class MSImage
{
public static byte[] ConvertToByte(FileUpload hpf)
{
try
{
if (hpf.HasFile)
{
Stream fs = hpf.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
return bytes;
}
}
catch { }
return null;
}
public static string ConvertToImage(byte[] imagedata)
{
try
{
if (imagedata != null && imagedata.Length > 0)
return Convert.ToBase64String(imagedata);
}
catch { }
return null;
}
}
Am I saving the image in a wrong way or is it the loading that causes the issue?
EDIT:
I just found out that this code is the problem:
takzir2.InnerHtml = "<div class='msbgimage' style=\"background-image:url(data:" + (string)ms[Database.MSImageType] + ";base64, " + imagedata + ")\"></div>";
I tried using a div that has runat="server" and it worked with div.Style["background-image"], but how can I make it work with InnerHtml?
I'm using following Code to convert my Images, maybe you find a difference...
static string Image2Base64(Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
static Bitmap Base642Image(string base64image)
{
try
{
byte[] imageBytes = Convert.FromBase64String(base64image);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Bitmap image = (Bitmap)Image.FromStream(ms, true);
return image;
}
catch { return null; }
}
I hope this might help you...
I just found the solution (It's a silly one though):
This line of code was causing the problem:
takzir2.InnerHtml = "<div class='msbgimage' style=\"background-image:url(data:" + (string)ms[Database.MSImageType] + ";base64, " + imagedata + ")\"></div>";
I changed the end of it from:
";base64, " + imagedata + ")\"></div>";
To:
";base64," + imagedata + ")\"></div>";
The space between ";base64," to imagedata was causing it because InnerHtml didn't replace the space character with %20.
Following is the code to retrieve image from database and then saving it to a folder.
public string BinarytoNewsImage(int ID)
{
byte[] btimage = null;
string image = "";
string filename = null;
int mediaid;
DataSet dsNews = new DataSet();
adp = new SqlDataAdapter("Select Top 1 * from tblNew Where intNewId=" + ID, offcon);
adp.Fill(dsNews, "tblNews1");
if (dsNews.Tables["tblNews1"].Rows.Count > 0)
{
if (dsNews.Tables["tblNews1"].Rows[0]["strImage"] != DBNull.Value)
{
btimage = (byte[])dsNews.Tables["tblNews1"].Rows[0]["strImage"];
mediaid = Convert.ToInt32(dsNews.Tables["tblNews1"].Rows[0]["intMediaId"].ToString());
filename = dsNews.Tables["tblNews1"].Rows[0]["strfilename"].ToString();
image = BinarytoImage(btimage, mediaid);
}
else
{
filename = dsNews.Tables["tblNews1"].Rows[0]["strfilename"].ToString();
image = "http://www.patrika.com/media/" + filename;
}
}
return image;
}
public string BinarytoImage(byte[] stream, int ID)
{
string ImagePath = "";
string Image = ID + ".jpg";
var URL = System.Configuration.ConfigurationManager.AppSettings["ImagePath"].ToString();
string FolderName = new Uri(URL).LocalPath;
var help = HttpContext.Current.Server.MapPath(FolderName);
if (Directory.Exists(HttpContext.Current.Server.MapPath(FolderName)))
{
string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(FolderName), ID + ".jpg");
if (files.Length > 0)
{
ImagePath = URL + ID + ".jpg";
}
else
{
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
img.Save(help + ID + ".jpg", System.Drawing.Imaging.ImageFormat.Gif);
img.Dispose();
img = null;
ImagePath = URL + ID + ".jpg";
}
}
}
return ImagePath;
}
Everything is working fine the images are saving to a folder but my problem is images are getting blur after retrieval.
I just don't know the reason as when I am using another code for retrieval than images are coming fine but are not saved to folder:
DataSet dsNews = new DataSet();
adp = new SqlDataAdapter("Select Top 1 * from tblNew Where intNewId=901371", con);
adp.Fill(dsNews, "tblNews1");
if (dsNews.Tables["tblNews1"].Rows[0]["strImage"] != DBNull.Value)
{
byte[] btimage = (byte[])dsNews.Tables["tblNews1"].Rows[0]["strImage"];
Response.ContentType = "image/jpeg";
Response.BinaryWrite(btimage);
}
I need those images to be saved to folder so that I don't have to call database after once image comes.
Wouldn't it help to change this line
img.Save(help + ID + ".jpg", System.Drawing.Imaging.ImageFormat.Gif);
to store it as JPEG rather? as that's the source format
EDIT:
Your are not moving the stream pointer back to the start.
Try change these lines:
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
...
To
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
MS.Seek(0, SeekOrigin.Begin);
System.Drawing.Image img = System.Drawing.Image.FromStream(MS);
...
I write the common method, all is ok.
Maybe your byte[]stream is not right,pls check.
byte[] stream = File.ReadAllBytes(#"D:\YWG\123.jpg");
using (MemoryStream MS = new MemoryStream(stream, 0, stream.Length))
{
MS.Write(stream, 0, stream.Length);
using (Image img = Image.FromStream(MS))
{
img.Save(#"D:\dd.jpg", System.Drawing.Imaging.ImageFormat.Gif);
}
}
I see the dest file "dd.jpg" is ok.