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.
Related
my question is how to upload byte array to server ?
I am already convert it to byte array like this :
Stream stream = ContentResolver.OpenInputStream(data.Data);
Bitmap bitmap = BitmapFactory.DecodeStream(stream);
MemoryStream memStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, memStream);
byte[] picData;
picData = memStream.ToArray();
Now I want to upload picData to the server in folder "pics"
public string UploadToServer(byte[] image)
{
try
{
MemoryStream ms = new MemoryStream(image);
var i = Bitmap.FromStream(ms);
string time = DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss");
string Filename = "IMG_" + time + ".png";
string UploadPath = HttpContext.Current.Server.MapPath("~/Image");
if (!Directory.Exists(UploadPath))
Directory.CreateDirectory(UploadPath);
string NewFilePath = Path.Combine(UploadPath, Filename);
File.WriteAllBytes(NewFilePath, image);
return Filename;
}
catch (Exception)
{
throw;
}
}
I'm comparing two images; the source is in my solution (and saving it to memory stream) and other I am downloading using 'WebClient' converting it to bytes and then saving it in a stream, then comparing the streams.
They are exactly the same image. However my code produces different hash strings, so the 'If Equals' produces a false.
I'm thinking the downloading and saving of the image is altering the string.
The code:
public void CompareImages(string icon)
{
WebClient wc = new WebClient();
MemoryStream ms = new MemoryStream();
Image expectedImage = Image.FromFile(AppConfig.ToolsFilesFolderName + string.Format("\\" + icon +".png"));
expectedImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
String firstBitmap = Convert.ToBase64String(ms.ToArray());
ms.Position = 0;
MemoryStream ms2 = null;
byte[] bytes;
var baseEventType = _driver.FindElement(By.XPath("//div[#id='EventsView2_tv']/div/div")); ///div/div/div[19] //what i need to do is expand all of them and then
int count = 0;
var eventTypeExists = baseEventType.FindElements(By.TagName("tr"));
for (int i = 0; i < eventTypeExists.Count; i++)
{
if (i>30)
return;
if (eventTypeExists[i].Text.Trim().ToLower().Equals(icon.ToLower()))
{
var imgPath = eventTypeExists[i].FindElement(By.XPath("td[3]/img"));
var imageUrl = imgPath.GetAttribute("src");
bytes = wc.DownloadData(imageUrl);
ms2 = new MemoryStream(bytes);
Image actualImage = Image.FromStream(ms2);
actualImage.Save(ms2, System.Drawing.Imaging.ImageFormat.Png);
String secondBitmap = Convert.ToBase64String(ms2.ToArray());
if (firstBitmap.Equals(secondBitmap))
{
Reporter.ReportNote(string.Format("'{0}' icon in '{1}' is correct",
icon, ScenarioContext.Current["contractName"] + "/" + eventTypeExists[i].FindElement(By.XPath("../../../../table[" + (i - 2) + "]")).Text),
Status.Pass);
}
else
{
Reporter.ReportNote(string.Format("Icons are not correct, offending image is located within '{0}'",
ScenarioContext.Current["contractName"] + "/" + eventTypeExists[i].FindElement(By.XPath("../../../../table[" + (i - 2) +"]")).Text),
Status.Done);
}
ms2.Dispose();
}
count++;
}
ms.Dispose();
wc.Dispose();
}
I have a camerapage which takes a picture, resizes it to a thumbnail and saves this resized image to a file locally on the android phone. I then try to send this uri-string to a viewmodel which is supposed to set its ImageSource property from this uri. I am currently unable to load the image from the url.
Here is my code:
In CameraPage(inside Take photo method)
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
using (var imageStream = new MemoryStream())
{
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 40, imageStream);
image.Recycle();
imageBytes = imageStream.ToArray();
var thumbnail =await DependencyService.Get<IPicResizer>().GetResizedImage(imageBytes);
// Temporary file to store the downloaded image
Java.IO.File tmpFile = new Java.IO.File(documentsPath + "/"+fileName + ".jpg");
tmpFile.ParentFile.Mkdirs();
// String path = MediaStore.Images.Media.InsertImage(this.Context.ContentResolver, documentsPath, fileName, ""); //(this.Context.ContentResolver, image, imgName.ToString(), null);
uri = Android.Net.Uri.Parse(tmpFile.Path);
// The FileOutputStream to the temporary file
var fOutStream = new FileOutputStream(tmpFile);
try
{
fOutStream.Write(thumbnail, 0, thumbnail.Length);
fOutStream.Flush();
fOutStream.Close();
DialogService.HideLoading();
DialogService.ShowSuccess("Saved picture at: " + uri.ToString());
}
catch (Java.IO.FileNotFoundException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
catch (Java.IO.IOException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
camera.StartPreview();
await App.Current.MainPage.Navigation.PushModalAsync(new InfoPage(imageBytes, tmpFile.AbsolutePath), false);
}
InfoPages view model:
ImageSource Source {get;set;}
public InfoViewModel(byte[] image, string imageUri)
{
if (image != null)
{
_image = image;
imageurl = new Uri("file:///" + imageUri, UriKind.Absolute);
Source = ImageSource.FromUri(imageurl);
}
}
All help is appreciated :)
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.
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[]));
}
}