public Image(Bitmap bmp) { //load code Pixel np=new Pixel(); m_width = (uint)bmp.Width; m_height = (uint)bmp.Height; m_needFlush = false; if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { m_components = 3; } else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { m_components = 4; } else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { m_components = 1; } ImageConverter imageConverter = new ImageConverter(); m_buffer = (byte[])imageConverter.ConvertTo(bmp, typeof(byte[])); }
private string ImageToBase64(Image img) { var imgConv = new ImageConverter(); var buffer = (byte[])imgConv.ConvertTo(img, typeof(byte[])); return Convert.ToBase64String(buffer, Base64FormattingOptions.None); }
private Tools() { _logger = new Logger(); _crossControl = new ControlCrossThreading(); _imageConverter = new ImageConverter(); _desktopViewerUtils = new RemotingUtils(); _cryptography = new Cryptography(); _genericMethods = new GenericMethods(); _dataCompression = new DataCompression(); }
public void ImageAsBase64ShouldReturnProperBase64String() { ImageConverter target = new ImageConverter(); string path = StrixPlatform.Environment.WorkingDirectory + @"\TestFiles\Strix_losuiltje.png"; int width = 100; int height = 100; string expected = "data:image/.png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAABkCAYAAADzJqxvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABBVSURBVHhe7Z0JVBRHGsdxN3vmkOkBjHc8YozXZjcb6RlQNGpMoptoIolGnJ4BRdFgRFHBi6BG8cIVVBS88lS8QU1EUSGK9423RlFRoyK3b3eTzW62tr6erp4erIFp6OlpSOq93wOGruP7T3Xdh0dtcybjC60sRs8gjmXmcQZmJ+aC2aB7iPkX/v0n/Pl/8O/l+OcdzBGzgVlrYj2jzb5Mr8GdmReEYH5x4AIDPX4dbNR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actual = target.ImageAsBase64(path, width, height); Assert.AreEqual(expected, actual); }
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { int row = 0; foreach(ImageInfo image in images) { Invoke(new InvokeRunningImageRow(RunningImageRow), row); DateTime start = DateTime.Now; ImageInkFinder finder = new ImageConverter().GetImageInkFinder(image.FullFileName); image.IsDot = finder.IsInk(); image.Time = DateTime.Now - start; Invoke(new InvokeViewImageRow(ViewImageRow), image, row); row++; } }
private static BitmapImage GetBitmapImage(byte[] image) { var ic = new ImageConverter(); var img = (System.Drawing.Image)ic.ConvertFrom(image); var bitmap = new Bitmap(img); var ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Png); ms.Position = 0; var bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = ms; bi.EndInit(); return bi; }
void CreateDefaultFile() { CommitInfo1.UserImage = Resources.DefaultUserImage; var imageConverter = new ImageConverter(); JArray jArray = new JArray(); jArray.Add(JsonConvert.SerializeObject(CommitInfo1, imageConverter)); jArray.Add(JsonConvert.SerializeObject(CommitInfo2, imageConverter)); jArray.Add(JsonConvert.SerializeObject(CommitInfo3, imageConverter)); JObject jObject = new JObject(); jObject["Commits"] = jArray; string jsonString = jObject.ToString(); PathHelper.WriteFile(filePath, jsonString); }
public void ResizeShouldResizeImageAndSaveToDisk() { ImageConverter target = new ImageConverter(); string path = StrixPlatform.Environment.WorkingDirectory + @"\TestFiles\uiltje.png"; string resultFile = StrixPlatform.Environment.WorkingDirectory + @"\TestFiles\uiltje_50_50.png"; System.IO.File.Delete(resultFile); int width = 50; int height = 50; bool overwrite = false; target.Resize(path, width, height, overwrite); bool result = false; if (System.IO.File.Exists(resultFile)) { System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(resultFile); result = bitmap.Width == 50 || bitmap.Height == 50; } Assert.IsTrue(result); }
public ImageTransformer() { converter = new ImageConverter(); }
private BitmapImage ShowPhoto(string filename) { ImageConverter ic = new ImageConverter(); BitmapImage image = ic.FromFileToImage(filename); return image; }
public string Upload(Image image) { ImageConverter converter = new ImageConverter(); byte[] imageData = (byte[])converter.ConvertTo(image, typeof(byte[])); if (imageData == null) { return(string.Empty); } using (WebClient w = new WebClient { Proxy = null }) { NameValueCollection values = new NameValueCollection { { "key", "Jk8hh9L" }, { "upload", Convert.ToBase64String(imageData) }, { "format", "xml" } }; XmlDocument xDoc = new XmlDocument(); try { byte[] response = w.UploadValues("http://i.zhyk.ru/api", values); xDoc.Load(new MemoryStream(response)); } catch (Exception ex) { return(ex.Message); } XmlNode statusNode = xDoc.SelectSingleNode("response/status_code"); if (statusNode == null) { return(string.Empty); } if (statusNode.InnerText.Equals("200")) { XmlNode imageNode = xDoc.SelectSingleNode("response/data/img_url"); if (imageNode != null) { return(imageNode.InnerText); } } else if (statusNode.InnerText.Equals("403")) { XmlNode statusTextNode = xDoc.SelectSingleNode("response/status_txt"); if (statusTextNode != null) { return("HostingError: " + statusTextNode.InnerText); } } return(string.Empty); } }
private void btnSave_Click(object sender, EventArgs e) { try { dbconnection sv = new dbconnection(); sv.thisConnection.Open(); SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT * FROM tenant", sv.thisConnection); SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter); DataSet thisDataSet = new DataSet(); thisAdapter.Fill(thisDataSet, "tenant"); DataRow thisRow = thisDataSet.Tables["tenant"].NewRow(); thisRow["name"] = textBoxName.Text; string value = ""; bool isChecked = radioBtnMale.Checked; if (isChecked) { value = radioBtnMale.Text; } else { value = radioBtnFemale.Text; } thisRow["gender"] = value.ToString(); thisRow["fatherName"] = textBoxFatherName.Text; thisRow["motherName"] = textBoxMotherName.Text; thisRow["phoneno"] = textBoxPhoneNo.Text; thisRow["email"] = textBoxEmail.Text; thisRow["balance"] = 0; thisRow["occupation"] = textBoxOccupation.Text; thisRow["country"] = textBoxCountry.Text; thisRow["address"] = textBoxAddress.Text; thisRow["rentDate"] = dateOfRent.Text; Image img = pictureBoxTenant.Image; byte[] arr; ImageConverter converter = new ImageConverter(); arr = (byte[])converter.ConvertTo(img, typeof(byte[])); thisRow["photo"] = arr; Image img2 = pictureBoxNID.Image; byte[] arr2; ImageConverter converter2 = new ImageConverter(); arr2 = (byte[])converter.ConvertTo(img2, typeof(byte[])); thisRow["nid"] = arr2; thisRow["nidno"] = textBoxNID.Text; thisDataSet.Tables["tenant"].Rows.Add(thisRow); thisAdapter.Update(thisDataSet, "tenant"); sv.thisConnection.Close(); dbconnection sv1 = new dbconnection(); sv1.thisConnection.Open(); string id = ""; string Sql = "select tenantId from tenant where name='" + textBoxName.Text.ToString() + "'"; SqlCommand cmd = new SqlCommand(Sql, sv1.thisConnection); SqlDataReader DR = cmd.ExecuteReader(); while (DR.Read()) { id = (DR["tenantId"].ToString()); } sv1.thisConnection.Close(); dbconnection sv2 = new dbconnection(); sv2.thisConnection.Open(); SqlCommand thisCommand = sv2.thisConnection.CreateCommand(); thisCommand.CommandText = "update flat set tenantId = '" + id + "' where flatName= '" + comboBoxFlatName.Text + "'"; thisCommand.Connection = sv2.thisConnection; thisCommand.CommandType = CommandType.Text; thisCommand.ExecuteNonQuery(); sv2.thisConnection.Close(); MessageBox.Show("Submitted"); } catch (Exception ex) { MessageBox.Show(ex.Message); } this.Close(); }
public static byte[] ImageToByteArray(Image img) //конвертируем картинку в массив байт { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(img, typeof(byte[]))); }
public static void Main(string[] args) { // -------------------------------------------------- // UserStoreオブジェクト作成 // -------------------------------------------------- // Real applications authenticate with Evernote using OAuth, but for the // purpose of exploring the API, you can get a developer token that allows // you to access your own Evernote account. To get a developer token, visit // https://sandbox.evernote.com/api/DeveloperToken.action String authToken = "your developer token"; if (authToken == "your developer token") { Console.WriteLine("Please fill in your developer token"); Console.WriteLine("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action"); return; } // Initial development is performed on our sandbox server. To use the production // service, change "sandbox.evernote.com" to "www.evernote.com" and replace your // developer token above with a token from // https://www.evernote.com/api/DeveloperToken.action String evernoteHost = "sandbox.evernote.com"; Uri userStoreUrl = new Uri("https://" + evernoteHost + "/edam/user"); TTransport userStoreTransport = new THttpClient(userStoreUrl); TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport); UserStore.Client userStore = new UserStore.Client(userStoreProtocol); // -------------------------------------------------- // バージョンチェック // -------------------------------------------------- bool versionOK = userStore.checkVersion("Evernote EDAMTest (C#)", Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR, Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR); Console.WriteLine("Is my Evernote API version up to date? " + versionOK); if (!versionOK) { return; } // -------------------------------------------------- // NoteStoreオブジェクト作成 // -------------------------------------------------- // Get the URL used to interact with the contents of the user's account // When your application authenticates using OAuth, the NoteStore URL will // be returned along with the auth token in the final OAuth request. // In that case, you don't need to make this call. String noteStoreUrl = userStore.getNoteStoreUrl(authToken); TTransport noteStoreTransport = new THttpClient(new Uri(noteStoreUrl)); TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport); NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol); // -------------------------------------------------- // ノートブック情報取得 // -------------------------------------------------- // List all of the notebooks in the user's account List<Notebook> notebooks = noteStore.listNotebooks(authToken); Console.WriteLine("Found " + notebooks.Count + " notebooks:"); foreach (Notebook notebook in notebooks) { Console.WriteLine(" * " + notebook.Name); } // -------------------------------------------------- // ノート作成(添付ファイルあり) // -------------------------------------------------- Console.WriteLine(); Console.WriteLine("Creating a note in the default notebook"); Console.WriteLine(); // To create a new note, simply create a new Note object and fill in // attributes such as the note's title. Note note = new Note(); note.Title = "Test note from EDAMTest.cs"; // To include an attachment such as an image in a note, first create a Resource // for the attachment. At a minimum, the Resource contains the binary attachment // data, an MD5 hash of the binary data, and the attachment MIME type. It can also // include attributes such as filename and location. ImageConverter converter = new ImageConverter(); byte[] image = (byte[])converter.ConvertTo(Resources.enlogo, typeof(byte[])); byte[] hash = new MD5CryptoServiceProvider().ComputeHash(image); Data data = new Data(); data.Size = image.Length; data.BodyHash = hash; data.Body = image; Resource resource = new Resource(); resource.Mime = "image/png"; resource.Data = data; // Now, add the new Resource to the note's list of resources note.Resources = new List<Resource>(); note.Resources.Add(resource); // To display the Resource as part of the note's content, include an <en-media> // tag in the note's ENML content. The en-media tag identifies the corresponding // Resource using the MD5 hash. string hashHex = BitConverter.ToString(hash).Replace("-", "").ToLower(); // The content of an Evernote note is represented using Evernote Markup Language // (ENML). The full ENML specification can be found in the Evernote API Overview // at http://dev.evernote.com/documentation/cloud/chapters/ENML.php note.Content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" + "<en-note>Here's the Evernote logo:<br/>" + "<en-media type=\"image/png\" hash=\"" + hashHex + "\"/>" + "</en-note>"; // Finally, send the new note to Evernote using the createNote method // The new Note object that is returned will contain server-generated // attributes such as the new note's unique GUID. Note createdNote = noteStore.createNote(authToken, note); Console.WriteLine("Successfully created new note with GUID: " + createdNote.Guid); }
//do update league info public void update() { try { Bitmap screenCap = (Bitmap)form.windowImage.Clone(); if (form.windowImage.Width < 10 || form.windowImage.Height < 10) { return; } /*look for the load screen*/ if (!outOfLoadScreen) { var w = form.windowImage; bool allBlack = true; for (int x = w.Width / 2; x < w.Width; x++) { for (int y = w.Height - 5; y < w.Height; y++) { var c = w.GetPixel(x, y); if (c.R != 0 || c.G != 0 || c.B != 0) { allBlack = false; break; } } } if (allBlack) //process the load screen { if (loadScreenInfo == null) //process the loadscreen for the first time. { parseLoadingScreen(); return; } /* * If the load screen has been processed, interpret the information in * loadScreenInfo and write it to the summonerInfo array as well as the log */ for (int i = 0; i < loadScreenInfo.topChampionCount; i++) // Top row of champions { if (summonerInfo[0][i] == null) { summonerInfo[0][i] = getSummonerInfo( (Bitmap)w, loadScreenInfo.minX + i * (loadScreenInfo.championWidth + loadScreenInfo.xpadding) - 1, loadScreenInfo.topPadding, loadScreenInfo.scale, i); if (summonerInfo[0][i] == null) { //form.scriptControl.log("System Exit"); //System.Environment.Exit(1); //update(); return; } else form.scriptControl.log("LoadScreen: Found top champion (" + summonerInfo[0][i].championCodeName + ") with " + summonerInfo[0][i].summonerSpell1 + " and " + summonerInfo[0][i].summonerSpell2); } } for (int i = 0; i < loadScreenInfo.botChampionCount; i++) // Bottom row of champions { if (summonerInfo[1][i] == null) { summonerInfo[1][i] = getSummonerInfo( (Bitmap)w, loadScreenInfo.minXBot + i * (loadScreenInfo.championWidth + loadScreenInfo.xpadding) - 1, w.Height - loadScreenInfo.topPadding - loadScreenInfo.championHeight - 2, loadScreenInfo.scale, i + 5); if (summonerInfo[1][i] == null) { //form.scriptControl.log("System Exit"); //System.Environment.Exit(1); //update(); return; } else form.scriptControl.log("LoadScreen: Found bot champion (" + summonerInfo[1][i].championCodeName + ") with " + summonerInfo[1][i].summonerSpell1 + " and " + summonerInfo[1][i].summonerSpell2); } } return; } else //in game now { form.scriptControl.raiseEvent("interfaceInit", ""); outOfLoadScreen = true; form.scriptControl.log("Left Load Screen"); foreach (var v in champData) { v.image.Dispose(); v.image = null; //Empty the champion data from the load screen } } } /* Set Current Hero Name */ if (heroName == "") { string curName = ""; double curRMS = double.MaxValue; double rms = 0; Bitmap bit, temp; temp = screenCap.Clone(LeagueUI.playerAvatar, System.Drawing.Imaging.PixelFormat.Undefined); Bitmap cBit = new Bitmap(temp, new System.Drawing.Size(120, 120)); temp.Dispose(); Rectangle r = new System.Drawing.Rectangle((int)(cBit.Width * (20.0 / 120.0)), (int)(cBit.Height * (20.0 / 120.0)), (int)(cBit.Width * (68.0 / 120.0)), (int)(cBit.Height * (72.0 / 120.0))); temp = cBit; cBit = cBit.Clone(r, System.Drawing.Imaging.PixelFormat.Undefined); temp.Dispose(); cBit.Save("championInfo\\champion.png"); // loop through heroes and find the one with the lowest rms diff. foreach (string c in cnames.Keys) { temp = new Bitmap(LeagueUtils.FileFinder.findChampImageFolder() + "\\" + c + "_Square_0.png"); bit = temp.Clone(r, System.Drawing.Imaging.PixelFormat.Undefined); temp.Dispose(); if (c.ToLower() == "garen") bit.Save("championInfo\\garen.png"); rms = calcRMSDiff(cBit, bit); bit.Dispose(); if (rms < curRMS) { curRMS = rms; curName = c; } bit.Dispose(); // System.Diagnostics.Debug.WriteLine(cnames[i] + " " + rms); } cBit.Dispose(); heroName = curName; //bit = new Bitmap(Preferences.leagueFolder + "\\air\\assets\\images\\champions\\" + heroName + "_Square_0.png"); System.Diagnostics.Debug.WriteLine("Hero Name" + heroName); form.scriptControl.log("Player Champion: " + heroName); } /* End Setting Hero Name */ /**********************************************************************/ /* Set Current Hero Level */ //int thinkLevel = 1; Bitmap wLevelBit, unResizedLevelBit; byte[] newImgBytes = new byte[1]; ImageConverter converter = new ImageConverter(); //System.Diagnostics.Debug.WriteLine(LeagueUI.cLevel); unResizedLevelBit = screenCap.Clone(LeagueUI.cLevel, System.Drawing.Imaging.PixelFormat.Undefined); wLevelBit = new Bitmap(unResizedLevelBit, new System.Drawing.Size(12, 8)); wLevelBit.Save("championInfo\\LEVEL_IMAGE.png"); unResizedLevelBit.Dispose(); /*if (firstLoad) { currentLevelImage = wLevelBit; currentImgBytes = (byte[])converter.ConvertTo(currentLevelImage, currentImgBytes.GetType()); currentLevel++; System.Diagnostics.Debug.WriteLine("Hero Level" + currentLevel); form.scriptControl.levelUp(); firstLoad = false; }*/ newImgBytes = (byte[])converter.ConvertTo(wLevelBit, newImgBytes.GetType()); for (int i = 0; i < currentImgBytes.Length && i < newImgBytes.Length; i++) { if (!(currentImgBytes[i] == newImgBytes[i]) && currentLevel < 18) { currentLevel++; System.Diagnostics.Debug.WriteLine("Hero Level" + currentLevel); form.scriptControl.levelUp(); currentLevelImage = wLevelBit; currentImgBytes = (byte[])converter.ConvertTo(currentLevelImage, currentImgBytes.GetType()); } } wLevelBit.Dispose(); /* End Setting Hero Level*/ /*Bitmap testBit = null; testBit = (Bitmap) form.windowImage.Clone(); testBit.Save("championInfo\\ScreenCap" + DateTime.Now.Second.ToString() + ".png"); testBit.Dispose();*/ /* Hero Abilities */ /* * Threshold for deciding when an ability is considered to be on cooldown, needs to be high enough to avoid false positives like with * Clarity (large amount of blue pixels) and low enough to allow long cooldown abilities to be counted (like with 3-digit white text) */ int cooldownThreshold = 300; Bitmap wAbilityBit, unResizedAbilityBit; /* * Cycle through the abilitiy rectangles and get the image from the screen cap saved at the start of the loop. * Save the bitmap into the bitmap array. * Look at each pixel and decide if its blue or a light shade of grey/white, then tally it to the variable blueCount * If bluecount is greater than the cooldownThreshold, then its considered to be on cooldown. * Dispose of the bitmap and continue on to the next one. */ for (int i = 0; i < 6; i++) { unResizedAbilityBit = screenCap.Clone(LeagueUI.spellRect[i], System.Drawing.Imaging.PixelFormat.Undefined); spellBitmaps[i] = new Bitmap(unResizedAbilityBit, new System.Drawing.Size(unResizedAbilityBit.Width * 2, unResizedAbilityBit.Height * 2)); //unResizedAbilityBit.Save("scripts\\Images\\ability_" + i + ".png"); wAbilityBit = new Bitmap(unResizedAbilityBit, new System.Drawing.Size(20, 20)); //wAbilityBit.Save("championInfo\\Ability_" + i + ".png"); int blueCount = 0; for (int y = 0; y < wAbilityBit.Height; y++) { for (int x = 0; x < wAbilityBit.Width; x++) { var c = wAbilityBit.GetPixel(x, y); if ((c.B >= c.G + 50 && c.B >= c.R + 50) || (c.R > 140 && c.B > 140 && c.G > 140)) blueCount++; } } //wAbilityBit.Save("championInfo\\BlueCount-" + blueCount.ToString() + ".png"); unResizedAbilityBit.Dispose(); wAbilityBit.Dispose(); if (blueCount >= cooldownThreshold) { spellCooldowns[i] = 1; //sc.log("blueCount " + i + ": " + blueCount); } else spellCooldowns[i] = 0; } /*********************************************************************/ /* Set Available Abilities */ // System.Diagnostics.Debug.WriteLine(canChooseAbility[0] + " " + canChooseAbility[1] + " " + canChooseAbility[2] + " " + canChooseAbility[3]); /* End Setting Available Abilities */ /*********************************************************************/ /* Set Health Percent */ /* Bitmap hBit = form.windowImage.Clone(LeagueUI.cHealth, System.Drawing.Imaging.PixelFormat.Undefined); SColor hColor; int hCount = 0; for (int i = 0; i < hBit.Width; i++) { for (int j = 0; j < hBit.Height; j++) { hColor = hBit.GetPixel(i, j); if (hColor.G > 100 && hColor.R < 100 && hColor.B < 100) hCount++; } } if (healthPixCount == -1) { healthPercent = 100.0; healthPixCount = hCount; } else { healthPercent = (double)hCount / (double)healthPixCount; } * */ //System.Diagnostics.Debug.WriteLine("health percent" + healthPercent); /* Set Mana/Energy Percent */ lastUpdate = DateTime.Now; } catch (Exception e) { sc.log("[ERROR] (" + e.Source + "): " + e.Message + "\n" + e.StackTrace); throw; } }
private void GetTrainees(List<PersonAndDbidsOperators.Person> operators) { TraineeByDate = new List<Trainee>(); Trainee trainee; DeserializeXml dx = new DeserializeXml(); foreach (PersonAndDbidsOperators.Person person in operators) { DateTime dateOfBirth; if (!string.IsNullOrEmpty(person.DateOfBirth)) dateOfBirth = DateTime.Parse(person.DateOfBirth); else dateOfBirth = DateTime.Now; DateTime regDate = DateTime.Parse(person.RegDate); DateTime lastTrainedDate = DateTime.Parse(person.LastTrainedDate); Byte[] buffer = null; ImageConverter ic = new ImageConverter(); buffer = ic.FromFileToByte(person.Photo); var installation = dx.DeserializeInstallation().InstallationOptions.Where(i => i.InstallationCode.Equals(person.Installation)).Select(i => i.InstallationName).First(); trainee = new Trainee { PID = person.PID, LastName = person.LastName, HomePhone = person.HomePhone, MobilePhone = person.MobilePhone, FirstName = person.FirstName, MiddleName = person.MiddleName, DateOfBirth = dateOfBirth, Gender = person.Gender, OfficePhone = person.OfficePhone, Fax = person.Fax, Photo = buffer, Email = person.Email, RankID = int.Parse(person.RankID), OfficeCode = person.OfficeCode, TypeOfPID = person.TypeOfPID, RegDate = regDate, JobTitle = person.JobTitle, PersonRemarks = person.PersonRemarks, OperatorType = person.OperatorType, Installation = person.Installation, InstallationName = installation.ToString(), LastTrainedDate = lastTrainedDate, Nationality = person.Nationality }; TraineeByDate.Add(trainee); } }
public override DataTemplate SelectTemplate( object item, DependencyObject container ) { DataTemplate template = null; bool useImageTemplate = false; if( ( item is byte[] ) || ( item is System.Drawing.Image ) ) { ImageConverter converter = new ImageConverter(); object convertedValue = null; try { convertedValue = converter.Convert( item, typeof( ImageSource ), null, System.Globalization.CultureInfo.CurrentCulture ); } catch( NotSupportedException ) { //suppress the exception, the byte[] is not an image. convertedValue will remain null } if( convertedValue != null ) useImageTemplate = true; } else if( item is ImageSource ) { useImageTemplate = true; } else if( item is bool ) { template = GenericContentTemplateSelector.BoolTemplate; } if( useImageTemplate ) { template = GenericContentTemplateSelector.ImageTemplate; DataGridContext dataGridContext = DataGridControl.GetDataGridContext( container ); DataGridControl parentGrid = ( dataGridContext != null ) ? dataGridContext.DataGridControl : null; } if( template == null ) template = base.SelectTemplate( item, container ); return template; }
protected void UploadScreenSplashButton_Click(object sender, EventArgs e) { Util util = new Util(); Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID]; if (util.CheckSessionTimeout(State, Response, "../Default.aspx")) return; if (UploadScreenSplash.UploadedFiles.Count > 0) { repeaterResultsScreenSplash.DataSource = UploadScreenSplash.UploadedFiles; repeaterResultsScreenSplash.DataBind(); repeaterResultsScreenSplash.Visible = true; string targetFolder = Server.MapPath(UploadScreenSplash.TargetFolder); foreach (UploadedFile file in UploadScreenSplash.UploadedFiles) { string name = file.GetName(); if (!name.ToLower().EndsWith(".jpg")) { SplashUploadMessage.Text = "File must be .jpg file"; return; } string file_path = targetFolder + @"\" + name; if (System.IO.File.Exists(file_path)) { byte[] image_data = File.ReadAllBytes(file_path); ImageConverter ic = new ImageConverter(); System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(image_data); Bitmap bitmap = new Bitmap(img); if (bitmap.Width != 320 || bitmap.Height != 460) { SplashUploadMessage.Text = "The image '" + name + "' is not 320 X 460"; return; } AmazonS3 s3 = new AmazonS3(); string file_name = name.Replace(" ", "_"); string url = s3.UploadFile(State, file_name, file_path); if (!url.StartsWith("http")) return; if (File.Exists(file_path)) File.Delete(file_path); util.SetApplicationSplashImage(State, State["ApplicationID"].ToString(), url); ScreenSplashButton.Visible = true; DeleteSplashImage.Visible = true; } } } else { repeaterResultsScreenSplash.Visible = false; SplashUploadMessage.Text = "Browse for a file"; } }
protected void Button1_Click(object sender, EventArgs e) { Session["uname"] = TextUname.Text; if (DropDownListSelectUser.Text == "User") { cmd = new SqlCommand("select * from voter where voterid='" + TextUname.Text + "' and password='******'", con); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { if (dr["block"].ToString() == "Block") { Label1.Text = "Your Account is blocked...!"; } else { if (dr["activate"].ToString() == "deactivate") { try { byte[] img = (byte[])dr["image"]; ImageConverter ic = new ImageConverter(); System.Drawing.Image img1 = (System.Drawing.Image)ic.ConvertFrom(img); Bitmap bmp1 = new Bitmap(img1); if (FileUpload1.HasFile) { using (BinaryReader reader1 = new BinaryReader(FileUpload1.PostedFile.InputStream)) { bytes1 = reader1.ReadBytes(FileUpload1.PostedFile.ContentLength); } } else { Label1.Text = "Plz Upload File"; } System.Drawing.Image img2 = (System.Drawing.Image)ic.ConvertFrom(bytes1); Bitmap bmp2 = new Bitmap(img2); //Calling Compare Function if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciCompareOk) { Session["u_name"] = TextUname.Text; Response.Redirect("Registration2.aspx"); } else if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciPixelMismatch) { Label1.Visible = true; Label1.Text = "Incorrect Image"; } else if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciSizeMismatch) { Label1.Visible = true; Label1.Text = "Incorrect Image"; } } catch (Exception ex) { Label1.Visible = true; Label1.Text = ex.Message.ToString(); } } else { try { byte[] img = (byte[])dr["image"]; ImageConverter ic = new ImageConverter(); System.Drawing.Image img1 = (System.Drawing.Image)ic.ConvertFrom(img); Bitmap bmp1 = new Bitmap(img1); if (FileUpload1.HasFile) { using (BinaryReader reader1 = new BinaryReader(FileUpload1.PostedFile.InputStream)) { bytes1 = reader1.ReadBytes(FileUpload1.PostedFile.ContentLength); } } else { Label1.Text = "Plz Upload File"; } System.Drawing.Image img2 = (System.Drawing.Image)ic.ConvertFrom(bytes1); Bitmap bmp2 = new Bitmap(img2); //Calling Compare Function if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciCompareOk) { Session["u_name"] = TextUname.Text; Response.Redirect("welcomeuser.aspx"); } else if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciPixelMismatch) { Label1.Visible = true; Label1.Text = "Incorrect Image"; } else if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciSizeMismatch) { Label1.Visible = true; Label1.Text = "Incorrect Image"; } } catch (Exception ex) { Label1.Visible = true; Label1.Text = ex.Message.ToString(); } } } } else { Label1.Text = "Invalid User Name or Password"; // Response.Write("<script> alert('Invalid User Name or Password') ;</script> "); } } else { if (DropDownListSelectUser.Text == "Admin") { cmd = new SqlCommand("select * from admin where user_name='" + TextUname.Text + "' and password='******'", con); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Session["uname"] = TextUname.Text; Response.Redirect("welcomeadmin.aspx"); } else { Label1.Text = "Invalid User Name or Password"; } } } }
public override DataTemplate SelectTemplate( object item, DependencyObject container ) { if( item == null ) return base.SelectTemplate( item, container ); DataTemplate template = null; if( ( item is byte[] ) || ( item is System.Drawing.Image ) ) { bool useImageTemplate = false; try { var converter = new ImageConverter(); useImageTemplate = ( converter.Convert( item, typeof( ImageSource ), null, CultureInfo.CurrentCulture ) != null ); } catch( NotSupportedException ) { //suppress the exception, the byte[] is not an image. convertedValue will remain null } if( useImageTemplate ) { template = GenericContentTemplateSelector.GetImageTemplate( container ); } } else if( item is ImageSource ) { template = GenericContentTemplateSelector.GetImageTemplate( container ); } else if( item is bool ) { template = GenericContentTemplateSelector.BoolTemplate; } if( template == null ) { template = GenericContentTemplateSelector.GetCommonTemplate( item, container ); } if( template != null ) return template; return base.SelectTemplate( item, container ); }
public ActionResult GetInvoice(Int32 Invoice_ID, Boolean AutoPrint) { List <spGet_InvoiceBillTo_Result> B = db.spGet_InvoiceBillTo(Invoice_ID).ToList(); ViewData["BillTo"] = B; ViewData["Rep"] = B[0].Rep; ViewData["RepPhone"] = B[0].RepPhone; List <spGet_InvoiceShipTo_Result> S = db.spGet_InvoiceShipTo(Invoice_ID).ToList(); ViewData["ShipTo"] = S; ViewData["EmailAddress"] = B[0].client_broker_email; List <spGet_InvoiceInfo_Result> I = db.spGet_InvoiceInfo(Invoice_ID).ToList(); ViewData["RepNotes"] = I[0].email_info; ViewData["Info"] = I; if (string.IsNullOrEmpty(I[0].Stamp)) { ViewData["StampDisplay"] = "none"; } else { ViewData["StampDisplay"] = "block"; } ViewData["Stamp"] = I[0].Stamp; if (I[0].Stamp == "PAID") { ViewData["StampLoc"] = "342px"; } else { ViewData["StampLoc"] = "307px"; } ViewData["DisplayedNotes"] = I[0].displayed_notes; List <spGet_InvoicePayment_Result> P = db.spGet_InvoicePayment(Invoice_ID).ToList(); ViewData["Payment"] = P; List <spGet_InvoiceItems_Result> model = db.spGet_InvoiceItems(Invoice_ID).ToList(); ViewData["Items"] = model.Count(); Int32 Qty = Convert.ToInt32(model.Sum(item => item.Qty)); ViewData["Qty"] = Qty; Double Cost = Convert.ToDouble(model.Sum(item => item.Qty * item.Cost)); Double Price = Convert.ToDouble(model.Sum(item => item.Qty * item.Price)); ViewData["Price"] = String.Format("{0:c}", Price); ViewData["ShippingTotal"] = String.Format("{0:c}", I[0].invoice_total_shipping_cost); ViewData["TaxTotal"] = String.Format("{0:c}", I[0].invoice_total_taxes); ViewData["OtherExpensesTotal"] = String.Format("{0:c}", I[0].invoice_total_expense); ViewData["GrandTotal"] = String.Format("{0:c}", I[0].invoice_total); ViewData["BalanceDue"] = String.Format("{0:c}", I[0].invoice_balance_due); ViewData["DueDate"] = I[0].invoice_due_date; ViewData["Agent"] = I[0].Agent; ViewData["SalesDate"] = I[0].create_date; ViewData["Invoice"] = Invoice_ID; ViewData["DeliveryMethod"] = I[0].DeliveryMethod; ViewData["DisplayNotes"] = I[0].displayed_notes; ViewData["ExternalPO"] = I[0].external_PO; ViewData["TicketRequestID"] = I[0].ticket_request_id; ViewData["StatusDate"] = I[0].StatusDate; System.Drawing.Image myimg = Code128Rendering.MakeBarcodeImage(Invoice_ID.ToString(), int.Parse("1"), true); ImageConverter _imageConverter = new ImageConverter(); byte[] xByte = (byte[])_imageConverter.ConvertTo(myimg, typeof(byte[])); var base64 = Convert.ToBase64String(xByte); var imgSrc = String.Format("data:image/gif;base64,{0}", base64); ViewData["Barcode"] = imgSrc; ViewData["AutoPrint"] = AutoPrint; return(PartialView(model)); }
public static Byte[] ConvertImageToByteArray(Bitmap image) { var ic = new ImageConverter(); return ic.ConvertTo(image, typeof(byte[])) as byte[]; }
private void DoProcessing(IProgress <bool> oProgress, string filePath, CatalogExportType export, string[] a_sFiles) { var sbOutput = new StringBuilder(); if (export == CatalogExportType.CSV) { string strSeperator = ","; sbOutput.AppendLine(string.Join(strSeperator, "Datei", "Datum")); foreach (var file in a_sFiles.Select(x => new { file = x, time = File.GetLastWriteTime(x) }).OrderBy(x => x.time)) { try { if (_parentForm.TokenSource?.IsCancellationRequested ?? true) { return; } var ct = file.time; var name = Path.GetFileName(file.file); sbOutput.AppendLine(string.Join(strSeperator, name, ct)); oProgress?.Report(true); if (_parentForm.TokenSource?.IsCancellationRequested ?? true) { return; } } catch { } } } else { var ic = new ImageConverter(); sbOutput.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\">"); sbOutput.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sbOutput.AppendLine("<head>"); sbOutput.AppendLine("<title>Katalog</title>"); sbOutput.AppendLine("</head>"); sbOutput.AppendLine("<body>"); sbOutput.AppendLine("<table style=\"width:100%\">"); sbOutput.AppendLine("<tr>"); sbOutput.AppendLine("<th>Datei</th>"); sbOutput.AppendLine("<th>Datum</th>"); sbOutput.AppendLine("<th>Vorschau</th>"); sbOutput.AppendLine("</tr>"); foreach (var file in a_sFiles.Select(x => new { file = x, time = File.GetLastWriteTime(x) }).OrderBy(x => x.time)) { try { if (_parentForm.TokenSource?.IsCancellationRequested ?? true) { return; } sbOutput.AppendLine("<tr>"); var ct = file.time; var name = Path.GetFileName(file.file); var addTN = false; string imagestring = null; addTN = file.file.IsImage(out var thumbnail); sbOutput.AppendLine($"<td>{name}</td>"); sbOutput.AppendLine($"<td>{ct}</td>"); if (addTN) { var buffer = (byte[])ic.ConvertTo(thumbnail, typeof(byte[])); imagestring = Convert.ToBase64String(buffer, Base64FormattingOptions.InsertLineBreaks); sbOutput.AppendLine($"<td><img src=\"data:image/png;base64,{imagestring}\"/></td>"); } else { sbOutput.AppendLine($"<td></td>"); } sbOutput.AppendLine("</tr>"); } catch { } } sbOutput.AppendLine("</body>"); sbOutput.AppendLine("</html>"); } File.WriteAllText(filePath, sbOutput.ToString()); }
protected void UploadButton_Click(object sender, EventArgs e) { Util util = new Util(); Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID]; if (util.CheckSessionTimeout(State, Response, "../Default.aspx")) return; if (UploadMessage.Text.Length > 0) return; int width = Convert.ToInt32(Width.Text); int height = Convert.ToInt32(Height.Text); if (UploadBackground.UploadedFiles.Count > 0) { string targetFolder = Server.MapPath(UploadBackground.TargetFolder); foreach (UploadedFile file in UploadBackground.UploadedFiles) { string name = file.GetName(); if (!name.EndsWith(".png") && !name.EndsWith(".jpg") && !name.EndsWith(".gif")) { UploadMessage.Text = "The image format for '" + name + "' is not allowed"; return; } string file_path = targetFolder + @"\" + name; if (System.IO.File.Exists(file_path)) { byte[] image_data = File.ReadAllBytes(file_path); ImageConverter ic = new ImageConverter(); System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(image_data); Bitmap bitmap = new Bitmap(img); if (bitmap.Width != width || bitmap.Height != height) { UploadMessage.Text = "The image '" + name + "' is not " + Width.Text + " X " + Height.Text; return; } string file_name = util.FilterWebFileName(name); string save_file_path = HttpRuntime.Cache["TempFilesPath"].ToString() + State["Username"].ToString() + "." + file_name; try { if (File.Exists(save_file_path)) File.Delete(save_file_path); File.WriteAllBytes(save_file_path, image_data); File.Delete(file_path); } catch { //Trying to overwrite the same file } AmazonS3 s3 = new AmazonS3(); string url = s3.UploadFile(State, file_name, save_file_path); if (!url.StartsWith("http")) return ; if (File.Exists(save_file_path)) File.Delete(save_file_path); ImageSource.Text = url; UploadMessage.Text = "Upload Successful. Click Close."; } } } else { UploadMessage.Text = "Browse for a file"; } }
public static byte[] TryCastByteArray(Image image) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(image, typeof(byte[]))); }
private void House_Load(object sender, EventArgs e) { housesDto houseCurrent = Dashboard.houseCurrent; houseCurrentNow = houseCurrent; if (houseCurrent == null) { } else { name.Text = houseCurrent.name; type.Text = houseCurrent.type; location.Text = houseCurrent.location; area.Text = houseCurrent.area.ToString(); priceheactar.Text = houseCurrent.priceperhectar.ToString(); totalprice.Text = houseCurrent.totalprice.ToString(); for_.Text = houseCurrent.for_; finishing.Text = houseCurrent.finishing; company.Text = houseCurrent.company; finishing.Text = houseCurrent.finishing; finishing.Text = houseCurrent.finishing; if (houseCurrent.status == null || houseCurrent.status == false) { status.Text = "Not Available"; } else { status.Text = "Available"; } ImageConverter ic1 = new ImageConverter(); Image img1; Bitmap bitmap1; //PictureBox picture = new PictureBox(); ; if (houseCurrent.photoone == null || houseCurrent.photoone.Length < 100) { Console.WriteLine("hhhhhh"); } else { img1 = (Image)ic1.ConvertFrom(houseCurrent.photoone); bitmap1 = new Bitmap(img1); pictureBox1.Image = img1; pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } ImageConverter ic2 = new ImageConverter(); Image img2; Bitmap bitmap2; //PictureBox picture = new PictureBox(); ; if (houseCurrent.phototwo == null || houseCurrent.photoone.Length < 100) { Console.WriteLine("hhhhhh"); } else { img2 = (Image)ic2.ConvertFrom(houseCurrent.phototwo); bitmap2 = new Bitmap(img2); pictureBox2.Image = img2; pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage; } ImageConverter ic3 = new ImageConverter(); Image img3; Bitmap bitmap3; //PictureBox picture = new PictureBox(); ; if (houseCurrent.photothree == null || houseCurrent.photoone.Length < 100) { Console.WriteLine("hhhhhh"); } else { img3 = (Image)ic2.ConvertFrom(houseCurrent.photothree); bitmap3 = new Bitmap(img3); pictureBox3.Image = img3; pictureBox3.SizeMode = PictureBoxSizeMode.StretchImage; } } }
private void ROL_021_Rpt_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e) { try { //(sender as XtraReport).PrintingSystem.Document.AutoFitToPagesWidth = 1; lbl_fecha.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"); lbl_empresa.Text = empresa; lbl_usuario.Text = usuario; int IdEmpresa = p_IdEmpresa.Value == null ? 0 : Convert.ToInt32(p_IdEmpresa.Value); int IdNomina = p_IdNomina.Value == null ? 0 : Convert.ToInt32(p_IdNomina.Value); int IdNominaTipo = p_IdNominaTipo.Value == null ? 0 : Convert.ToInt32(p_IdNominaTipo.Value); int IdPeriodo = p_IdPeriodo.Value == null ? 0 : Convert.ToInt32(p_IdPeriodo.Value); int IdSucursal = p_IdSucursal.Value == null ? 0 : Convert.ToInt32(p_IdSucursal.Value); int IdDivision = P_IdDivision.Value == null ? 0 : Convert.ToInt32(P_IdDivision.Value); int IdArea = P_IdArea.Value == null ? 0 : Convert.ToInt32(P_IdArea.Value); string TipoRubro = P_TipoRubro.Value == null ? "" : Convert.ToString(P_TipoRubro.Value); switch (TipoRubro) { case "I": lblNombreReporte.Text = "Reporte de rubros de ingresos"; xrPivotGrid1.OptionsView.ShowColumnTotals = true; xrPivotGrid1.OptionsView.ShowColumnGrandTotals = true; pivotGridField5.Visible = false; pivotGridField8.Visible = true; break; case "E": lblNombreReporte.Text = "Reporte de rubros de egresos"; xrPivotGrid1.OptionsView.ShowColumnTotals = false; xrPivotGrid1.OptionsView.ShowColumnGrandTotals = false; pivotGridField5.Visible = false; pivotGridField8.Visible = false; break; case "A": lblNombreReporte.Text = "Rol General"; xrPivotGrid1.OptionsView.ShowColumnTotals = false; xrPivotGrid1.OptionsView.ShowColumnGrandTotals = false; pivotGridField5.Visible = true; pivotGridField8.Visible = false; break; default: lblNombreReporte.Text = "Rol General"; xrPivotGrid1.OptionsView.ShowColumnTotals = false; xrPivotGrid1.OptionsView.ShowColumnGrandTotals = false; pivotGridField5.Visible = true; pivotGridField8.Visible = false; break; } ROL_021_Bus bus_rpt = new ROL_021_Bus(); List <ROL_021_Info> lst_rpt = bus_rpt.get_list(IdEmpresa, IdNomina, IdNominaTipo, IdPeriodo, IdSucursal, IdDivision, IdArea, TipoRubro); this.DataSource = lst_rpt; tb_empresa_Bus bus_empresa = new tb_empresa_Bus(); var emp = bus_empresa.get_info(IdEmpresa); lbl_empresa.Text = emp.em_nombre; if (emp != null && emp.em_logo != null) { ImageConverter obj = new ImageConverter(); lbl_imagen.Image = (Image)obj.ConvertFrom(emp.em_logo); } } catch (Exception) { throw; } }
/// <summary> /// Compare one image to another. /// </summary> /// <param name="image">The source image.</param> /// <param name="other">The target image.</param> /// <returns>0 if the images are the same, -1 if the image size differs, 1 if the pixels are different.</returns> public static int Compare(this Image image, Image other) { int returnValue = 0; if (image == null && other == null) { returnValue = 0; } else if (image == null) { returnValue = -1; } else if (other == null) { returnValue = -1; } else if (image.Size != other.Size) { returnValue = -1; } else { //NOTE: This is slower than I'd like. Haven't debugged enough to determine where the slowdown is occuring and how to mitigate it. ImageConverter imageConverter = new ImageConverter(); byte[] imageArray = (byte[])imageConverter.ConvertTo(image, typeof(byte[])); byte[] otherArray = (byte[])imageConverter.ConvertTo(other, typeof(byte[])); //NOTE: Testing if comparing the byte array is faster than hashing and then comparing the smaller hash SHA256Managed sha256Managed = new SHA256Managed(); byte[] imageHash = sha256Managed.ComputeHash(imageArray); byte[] otherHash = sha256Managed.ComputeHash(otherArray); /* * MD5 md5 = MD5.Create(); * byte[] imageHash = md5.ComputeHash(imageArray); * byte[] otherHash = md5.ComputeHash(otherArray); */ /* * return (Encoding.UTF8.GetString(imageHash).CompareTo(Encoding.UTF8.GetString(otherHash))); */ if (imageHash.Length != otherHash.Length) { returnValue = 1; } for (int i = 0; i < imageHash.Length && i < otherHash.Length && returnValue == 0; i++) { if (imageHash[i] != otherHash[i]) { returnValue = 1; } } /* * if (imageArray.Length != otherArray.Length) * { * returnValue = 1; * } * * for (int i = 0; i < imageArray.Length && i < otherArray.Length && returnValue == 0; i++) * { * if (imageArray[i] != otherArray[i]) * { * returnValue = 1; * } * } */ } return(returnValue); }
protected void UploadScreenSplashButton_Click(object sender, EventArgs e) { Util util = new Util(); Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID]; if (util.CheckSessionTimeout(State, Response, "../../Default.aspx")) return; if (UploadScreenSplash.UploadedFiles.Count > 0) { repeaterResultsScreenSplash.DataSource = UploadScreenSplash.UploadedFiles; repeaterResultsScreenSplash.DataBind(); repeaterResultsScreenSplash.Visible = true; string targetFolder = Server.MapPath(UploadScreenSplash.TargetFolder); foreach (UploadedFile file in UploadScreenSplash.UploadedFiles) { string name = file.GetName(); string file_path = targetFolder + @"\" + name; if (System.IO.File.Exists(file_path)) { byte[] image_data = File.ReadAllBytes(file_path); ImageConverter ic = new ImageConverter(); System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(image_data); Bitmap bitmap = new Bitmap(img); int expected_width = Constants.IPHONE_DISPLAY_WIDTH; int expected_height = Constants.IPHONE_SCROLL_HEIGHT; switch (State["SelectedDeviceType"].ToString()) { case Constants.IPAD: expected_width = Constants.IPAD_DISPLAY_WIDTH; expected_height = Constants.IPAD_SCROLL_HEIGHT; break; case Constants.ANDROID_TABLET: expected_width = Constants.ANDROID_TABLET_DISPLAY_WIDTH; expected_height = Constants.ANDROID_TABLET_SCROLL_HEIGHT; break; case Constants.IPHONE: expected_width = Constants.IPHONE_DISPLAY_WIDTH; expected_height = Constants.IPHONE_SCROLL_HEIGHT; break; case Constants.ANDROID_PHONE: expected_width = Constants.ANDROID_PHONE_DISPLAY_WIDTH; expected_height = Constants.ANDROID_PHONE_SCROLL_HEIGHT; break; } if (bitmap.Width != expected_width || bitmap.Height != expected_height) { SplashUploadMessage.Text = "The image '" + name + "' is not the right size"; return; } AmazonS3 s3 = new AmazonS3(); string file_name = name.Replace(" ", "_"); string url = s3.UploadFile(State, file_name, file_path); if (!url.StartsWith("http")) return; if (File.Exists(file_path)) File.Delete(file_path); util.SetApplicationSplashImage(State, State["ApplicationID"].ToString(), url); ScreenSplashButton.Visible = true; DeleteSplashImage.Visible = true; } } } else { repeaterResultsScreenSplash.Visible = false; SplashUploadMessage.Text = "Browse for a file"; } }
private void LoadSlike(int SlikaId) { var result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { var fileName = openFileDialog1.FileName; var file = File.ReadAllBytes(fileName); Image image = Image.FromFile(fileName); if (SlikaId == 1) { request.Slika1 = file; txtSlikaInput1.Text = fileName; int resizedImgWidth = 300; int resizedImgHeight = 300; int croppedImgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgWidth"]); int croppedImgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgHeight"]); //if (image.Width > resizedImgWidth) //{ Image resizedImg = UIHelper.ResizeImage(image, new Size(resizedImgWidth, resizedImgHeight)); ImageConverter imgCon = new ImageConverter(); request.SlikaThumb1 = (byte[])imgCon.ConvertTo(resizedImg, typeof(byte[])); pictureBox1.Image = resizedImg; //} } else if (SlikaId == 2) { request.Slika2 = file; txtSlikaInput2.Text = fileName; int resizedImgWidth = 300; int resizedImgHeight = 300; int croppedImgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgWidth"]); int croppedImgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgHeight"]); //if (image.Width > resizedImgWidth) //{ Image resizedImg = UIHelper.ResizeImage(image, new Size(resizedImgWidth, resizedImgHeight)); ImageConverter imgCon = new ImageConverter(); request.SlikaThumb2 = (byte[])imgCon.ConvertTo(resizedImg, typeof(byte[])); pictureBox2.Image = resizedImg; //} } else if (SlikaId == 3) { request.Slika3 = file; txtSlikaInput3.Text = fileName; int resizedImgWidth = 300; int resizedImgHeight = 300; int croppedImgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgWidth"]); int croppedImgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgHeight"]); //if (image.Width > resizedImgWidth) //{ Image resizedImg = UIHelper.ResizeImage(image, new Size(resizedImgWidth, resizedImgHeight)); ImageConverter imgCon = new ImageConverter(); request.SlikaThumb3 = (byte[])imgCon.ConvertTo(resizedImg, typeof(byte[])); pictureBox3.Image = resizedImg; //} } else if (SlikaId == 4) { request.Slika4 = file; txtSlikaInput4.Text = fileName; int resizedImgWidth = 300; int resizedImgHeight = 300; int croppedImgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgWidth"]); int croppedImgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgHeight"]); //if (image.Width > resizedImgWidth) //{ Image resizedImg = UIHelper.ResizeImage(image, new Size(resizedImgWidth, resizedImgHeight)); ImageConverter imgCon = new ImageConverter(); request.SlikaThumb4 = (byte[])imgCon.ConvertTo(resizedImg, typeof(byte[])); pictureBox4.Image = resizedImg; //} } else if (SlikaId == 5) { request.Slika5 = file; txtSlikaInput5.Text = fileName; int resizedImgWidth = 300; int resizedImgHeight = 300; int croppedImgWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgWidth"]); int croppedImgHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImgHeight"]); Image resizedImg = UIHelper.ResizeImage(image, new Size(resizedImgWidth, resizedImgHeight)); ImageConverter imgCon = new ImageConverter(); request.SlikaThumb5 = (byte[])imgCon.ConvertTo(resizedImg, typeof(byte[])); pictureBox5.Image = resizedImg; } } }
//todo: add all these convesions to code notes private static byte[] ToByteArray(this Bitmap bitmap) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(bitmap, typeof(byte[]))); }
private void SaveImage(string lastName, string firstName, string pid, string filename) { ImageConverter ic = new ImageConverter(); BitmapSource imageSource = (BitmapSource)imgDBIDSOperator.Source; ic.SaveImageToFile(filename, imageSource); }
private static byte[] ConvertToByteArray2(Image img) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(img, typeof(byte[]))); }
public void SetImage(int frame) { try { System.Windows.Controls.Image image = new System.Windows.Controls.Image(); var img = DcmImage.GetImage(frame); ImageConverter imgConv = new ImageConverter(); var bytes = (byte[])imgConv.ConvertTo(img, typeof(byte[])); MemoryStream ms = new MemoryStream(bytes); BitmapImage bmpImg = new BitmapImage(); bmpImg.BeginInit(); bmpImg.StreamSource = ms; bmpImg.EndInit(); image.Source = bmpImg; image.Width = image.Width * ScaledWidth; image.Height = image.Height * ScaledHeight; Grid.SetRow(image, 0); Grid.SetColumn(image, 0); CanvasGrid.Children.Add(image); } catch(Exception e) { MessageBox.Show("Error setting the image to the canvas: " + e.Message); } }
static byte[] IconByte(Icon ic, CardWinExplorerDataSource.SizeIcon size, bool maybeMinIcon) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(GetBitmap(ic, size, maybeMinIcon), typeof(byte[]))); }
private void AddSingleFrameImageToCanvas(ImageMatrix imageMtx, ref int i, ref int j) { Console.Out.WriteLine("Adding new SF image at Row: " + i + " Column: " + j); System.Windows.Controls.Image image = new System.Windows.Controls.Image(); var img = imageMtx.GetImage(0); ImageConverter imgConv = new ImageConverter(); var bytes = (byte[])imgConv.ConvertTo(img, typeof(byte[])); MemoryStream ms = new MemoryStream(bytes); BitmapImage bmpImg = new BitmapImage(); bmpImg.BeginInit(); bmpImg.StreamSource = ms; bmpImg.EndInit(); image.Source = bmpImg; image.Width = image.Width * ScaledWidth; image.Height = image.Height * ScaledHeight; Grid.SetRow(image, i); Grid.SetColumn(image, j); CanvasGrid.Children.Add(image); j++; }
public ImageTransformer(List <FileStatusLine> sourceRenameFilePairs, string folder) { converter = new ImageConverter(); this.fileStatusLines = sourceRenameFilePairs; savingDir = folder; }
private void AddMutliframedImageToCanvas(ImageMatrix imageMtx, ref int i, ref int j, int frames) { for (int frameIndex = 0; frameIndex < frames; frameIndex++, j++) { if (j >= Columns) { j = 0; i++; } Console.Out.WriteLine("Adding new MF image at Row: " + i + " Column: " + j); System.Windows.Controls.Image image = new System.Windows.Controls.Image(); var img = imageMtx.GetImage(frameIndex); ImageConverter imgConv = new ImageConverter(); var bytes = (byte[])imgConv.ConvertTo(img, typeof(byte[])); MemoryStream ms = new MemoryStream(bytes); BitmapImage bmpImg = new BitmapImage(); bmpImg.BeginInit(); bmpImg.StreamSource = ms; bmpImg.EndInit(); image.Source = bmpImg; image.Width = image.Width * ScaledWidth; image.Height = image.Height * ScaledHeight; Grid.SetRow(image, i); Grid.SetColumn(image, j); CanvasGrid.Children.Add(image); } }
static void Main(string[] args) { Console.WriteLine("Register Parse subclasses and init the ParseClient"); ParseObject.RegisterSubclass <Hello>(); ParseObject.RegisterSubclass <World>(); ParseClient.Initialize(new ParseClient.Configuration { ApplicationId = "myAppId", Server = "http://localhost:1337/parse/" }); Console.WriteLine("Generate an image to save on parse-server."); Bitmap flag = new Bitmap(10, 10); for (int x = 0; x < flag.Height; x++) { for (int y = 0; y < flag.Width; y++) { flag.SetPixel(x, y, Color.White); } } for (int x = 0; x < flag.Height; x++) { flag.SetPixel(x, x, Color.Red); } // Convert the new bitmap image to byte array for ParseFile ImageConverter converter = new ImageConverter(); byte[] bytes = (byte[])converter.ConvertTo(flag, typeof(byte[])); Parse.ParseFile flagImage = new ParseFile("flag.bmp", bytes); Console.WriteLine("Saving the image to parse-server."); Task fileContinuationTask = flagImage.SaveAsync().ContinueWith((antecedent) => { Console.WriteLine("Finished saving file to parse-server"); }); fileContinuationTask.Wait(); Console.WriteLine("Generate data to save on parse-server using subclassing"); World earth = new World { Name = "Earth", Message = "Hello from Earth!", Flag = flagImage }; World mars = new World { Name = "Mars", Message = "Hello from Mars!", Flag = flagImage }; World saturn = new World { Name = "Saturn", Message = "Hello from Saturn!", Flag = flagImage }; World jupiter = new World { Name = "Jupiter", Message = "Hello from Jupiter!", Flag = flagImage }; List <World> neighbors = new List <World>(); neighbors.Add(mars); neighbors.Add(saturn); neighbors.Add(jupiter); Hello hello = new Hello { World = earth, Neighbors = neighbors }; Console.WriteLine("Save subclass data to parse-server"); Task continuationTask = hello.SaveAsync().ContinueWith((antecedent) => { Console.WriteLine("Save Finished! Status:{0}", antecedent.Status.ToString()); }); continuationTask.Wait(); Console.WriteLine("Generate data to save on parse-server using ParseObject.Create"); var testObject = ParseObject.Create("World"); // Since World is subclassed use .Create() testObject["name"] = "Venus"; testObject["message"] = "Hello from Venus!"; testObject["flag"] = flagImage; Console.WriteLine("Save object data to parse-server"); Task contTask = testObject.SaveAsync().ContinueWith((antecedent) => { Console.WriteLine("Save TestObject Finished! Status:{0}", antecedent.Status.ToString()); }); contTask.Wait(); Console.ReadLine(); }
private void setSequentialImage() { int frame = 0; for (int i = 0; i < Rows; i++) { for (int j = 0; j < Columns && frame < Columns * Rows; j++, frame++) { Console.Out.WriteLine("Adding new SEQ image at Row: " + i + " Column: " + j); System.Windows.Controls.Image image = new System.Windows.Controls.Image(); var img = DcmImage.GetImage(frame); ImageConverter imgConv = new ImageConverter(); var bytes = (byte[])imgConv.ConvertTo(img, typeof(byte[])); MemoryStream ms = new MemoryStream(bytes); BitmapImage bmpImg = new BitmapImage(); bmpImg.BeginInit(); bmpImg.StreamSource = ms; bmpImg.EndInit(); image.Source = bmpImg; image.Width = image.Width * ScaledWidth; image.Height = image.Height * ScaledHeight; Grid.SetRow(image, i); Grid.SetColumn(image, j); CanvasGrid.Children.Add(image); } } }
private Task StartVideoStream() { if (VideoStream != null) { var outputFormat = VideoStream.OutputFormat; if (outputFormat == null) { throw new NegotiateException("Could not negotiate an video codec with the server."); } VideoFormat = outputFormat.Clone(); VideoSink = CreateVideoSink(); var currentInput = (IVideoInput)VideoSink; if (Options.VideoTranscode) { if (currentInput.InputFormat.IsPacketized) { VideoPacketizer = currentInput.InputFormat.ToEncoding().CreatePacketizer(); currentInput.AddInput(VideoPacketizer); currentInput = VideoPacketizer; } if (currentInput.InputFormat.IsCompressed) { VideoEncoder = currentInput.InputFormat.ToEncoding().CreateEncoder(); currentInput.AddInput(VideoEncoder); currentInput = VideoEncoder; } ResetVideoPipe = new ResetVideoPipe(currentInput.InputFormat); currentInput.AddInput(ResetVideoPipe); currentInput = ResetVideoPipe; } if (!currentInput.InputFormat.IsCompressed) { VideoDecoder = VideoFormat.ToEncoding().CreateDecoder(); VideoConverter = new ImageConverter(VideoDecoder.OutputFormat, currentInput.InputFormat); currentInput.AddInput(VideoConverter); currentInput = VideoConverter; currentInput.AddInput(VideoDecoder); currentInput = VideoDecoder; } if (!currentInput.InputFormat.IsPacketized) { VideoDepacketizer = VideoFormat.ToEncoding().CreateDepacketizer(); currentInput.AddInput(VideoDepacketizer); currentInput = VideoDepacketizer; } var streamOutput = null as VideoPipe; foreach (var output in VideoStream.Outputs) { if (output.InputFormat.IsEquivalent(VideoFormat, true)) { streamOutput = output as VideoPipe; } } currentInput.AddInput(streamOutput); if (VideoEncoder != null && !VideoEncoder.OutputFormat.IsFixedBitrate && Options.VideoBitrate.HasValue) { VideoEncoder.TargetBitrate = Options.VideoBitrate.Value; } } return(Task.CompletedTask); }
private void buttonGetInputFile_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"; openFileDialog.FilterIndex = 1; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == DialogResult.OK) { ImageConverter ic = new ImageConverter(openFileDialog.FileName); trainingData = ic.GetTrainingData(out idealData); MessageBox.Show("TRAINING DATA LOADED"); } openFileDialog.Dispose(); }
/// <summary> /// Converte um Bitmap em byte array /// </summary> /// <param name="instance">Bitmap a ser convertido</param> /// <returns>byte array convertido</returns> public static byte[] ToByteArray(this Bitmap instance) { var converter = new ImageConverter(); return((byte[])converter.ConvertTo(instance, typeof(byte[]))); }
public static byte[] BitmapToBytes(Image img) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[])); }
public static void SendRequest(string inputPath, string outputPath) { IPHostEntry host; string containerIP = "?"; string hostName = "mw-tf-server.uksouth.azurecontainer.io"; host = Dns.GetHostEntry(hostName); //; //Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { containerIP = ip.ToString(); } } //Create gRPC Channel var channel = new Channel(containerIP + ":8500", ChannelCredentials.Insecure); var client = new PredictionService.PredictionServiceClient(channel); //Check available models //var responce = client.GetModelMetadata(new GetModelMetadataRequest() //{ // ModelSpec = new ModelSpec() { Name = "model" }, // MetadataField = { "signature_def" } //}); //Console.WriteLine($"Model Available: {responce.ModelSpec.Name} Ver.{responce.ModelSpec.Version}"); //string imagePath = "C:/WebcamSnapshots/picture.png"; var request = new PredictRequest() { ModelSpec = new ModelSpec() { Name = "model", SignatureName = "serving_default" } }; Stream stream = new FileStream(inputPath, FileMode.Open); byte[] b; using (BinaryReader br = new BinaryReader(stream)) { b = br.ReadBytes((int)stream.Length); } string base64String = Convert.ToBase64String(b, 0, b.Length); //Console.WriteLine(base64String.Substring(0, 50)); request.Inputs.Add("input_image", TensorBuilder.CreateTensorFromString(base64String)); try { var predictResponse = client.Predict(request); var output = predictResponse.Outputs["output_image"]; var image_output0 = output.StringVal[0]; var stri = image_output0.ToString(Encoding.ASCII); //Console.WriteLine(stri); for (int i = 0; i < (stri.Length % 4); i++) { stri += "="; } //byte[] image_output1 = ASCIIEncoding.ASCII.GetBytes(stri); stri = stri.Replace('_', '/').Replace('-', '+'); byte[] test = Convert.FromBase64String(stri); //string savePath = "C:/WebcamSnapshots/csharp_prediction.png"; ImageConverter converter = new ImageConverter(); Image image = (Image)converter.ConvertFrom(test); image.Save(outputPath, ImageFormat.Png); } catch (Exception ex) { MessageBox.Show(ex.Message); } channel.ShutdownAsync().Wait(); }
public static byte[] ToByteArray(this Bitmap bitty) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(bitty, typeof(byte[])); }
private void SeedImages(ApplicationDbContext context) { string path = @"C:\Users\User1\Documents\GitHub\Hotel\Source\Web\Hotel.Web\Content\Images\"; List <Picture> pictures = new List <Picture>(); for (int i = 1; i < 4; i++) { Picture newPicture = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "0"), Image = ImageConverter.ImageToByteArray(path + "room" + i + ".jpg"), Name = "room" + i }; pictures.Add(newPicture); } for (int i = 1; i < 4; i++) { Picture newPicture = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "1"), Image = ImageConverter.ImageToByteArray(path + "restaurant" + i + ".jpg"), Name = "restaurant" + i }; pictures.Add(newPicture); } for (int i = 1; i < 4; i++) { Picture newPicture = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "3"), Image = ImageConverter.ImageToByteArray(path + "hall" + i + ".jpg"), Name = "hall" + i }; pictures.Add(newPicture); } for (int i = 1; i < 3; i++) { Picture newPicture = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "2"), Image = ImageConverter.ImageToByteArray(path + "piano-bar" + i + ".jpg"), Name = "bar" + i }; pictures.Add(newPicture); } Picture hotelPicture1 = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "4"), Image = ImageConverter.ImageToByteArray(path + "hotel1.jpg"), Name = "hotel1" }; pictures.Add(hotelPicture1); Picture hotelPicture2 = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "4"), Image = ImageConverter.ImageToByteArray(path + "hotel2.jpg"), Name = "hotel2" }; pictures.Add(hotelPicture2); Picture reception = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "4"), Image = ImageConverter.ImageToByteArray(path + "reception.jpg"), Name = "reception" }; pictures.Add(reception); for (int i = 1; i < 8; i++) { Picture newPicture = new Picture { Category = (ImageCategory)Enum.Parse(typeof(ImageCategory), "5"), Image = ImageConverter.ImageToByteArray(path + "spa" + i + ".jpg"), Name = "spa" + i }; pictures.Add(newPicture); } pictures.ForEach(s => context.Pictures.AddOrUpdate(p => p.Id, s)); }
public static void Main(string[] args) { // Real applications authenticate with Evernote using OAuth, but for the // purpose of exploring the API, you can get a developer token that allows // you to access your own Evernote account. To get a developer token, visit // https://sandbox.evernote.com/api/DeveloperToken.action String authToken = "your developer token"; if (authToken == "your developer token") { Console.WriteLine("Please fill in your developer token"); Console.WriteLine("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action"); Console.ReadLine(); return; } // Initial development is performed on our sandbox server. To use the production // service, change "sandbox.evernote.com" to "www.evernote.com" and replace your // developer token above with a token from // https://www.evernote.com/api/DeveloperToken.action String evernoteHost = "sandbox.evernote.com"; Uri userStoreUrl = new Uri("https://" + evernoteHost + "/edam/user"); TTransport userStoreTransport = new THttpClient(userStoreUrl); TProtocol userStoreProtocol = new TBinaryProtocol(userStoreTransport); UserStore.Client userStore = new UserStore.Client(userStoreProtocol); bool versionOK = userStore.checkVersion("Evernote EDAMTest (C#)", Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MAJOR, Evernote.EDAM.UserStore.Constants.EDAM_VERSION_MINOR); Console.WriteLine("Is my Evernote API version up to date? " + versionOK); if (!versionOK) { return; } // Get the URL used to interact with the contents of the user's account // When your application authenticates using OAuth, the NoteStore URL will // be returned along with the auth token in the final OAuth request. // In that case, you don't need to make this call. String noteStoreUrl = userStore.getNoteStoreUrl(authToken); TTransport noteStoreTransport = new THttpClient(new Uri(noteStoreUrl)); TProtocol noteStoreProtocol = new TBinaryProtocol(noteStoreTransport); NoteStore.Client noteStore = new NoteStore.Client(noteStoreProtocol); // List all of the notebooks in the user's account List<Notebook> notebooks = noteStore.listNotebooks(authToken); Console.WriteLine("Found " + notebooks.Count + " notebooks:"); foreach (Notebook notebook in notebooks) { Console.WriteLine(" * " + notebook.Name); } // Sample Code To Add A Notebook //Notebook newNoteBook = new Notebook(); //newNoteBook.Name = "Test Notebook"; //noteStore.createNotebook(authToken, newNoteBook); Console.WriteLine(); Console.WriteLine("Creating a note in the default notebook"); Console.WriteLine(); // To create a new note, simply create a new Note object and fill in // attributes such as the note's title. Note note = new Note(); note.Title = "Evernote Logo"; // To include an attachment such as an image in a note, first create a Resource // for the attachment. At a minimum, the Resource contains the binary attachment // data, an MD5 hash of the binary data, and the attachment MIME type. It can also // include attributes such as filename and location. ImageConverter converter = new ImageConverter(); byte[] image = (byte[])converter.ConvertTo(Resources.enlogo, typeof(byte[])); byte[] hash = new MD5CryptoServiceProvider().ComputeHash(image); Data data = new Data(); data.Size = image.Length; data.BodyHash = hash; data.Body = image; Resource resource = new Resource(); resource.Mime = "image/png"; resource.Data = data; // Now, add the new Resource to the note's list of resources note.Resources = new List<Resource>(); note.Resources.Add(resource); // To display the Resource as part of the note's content, include an <en-media> // tag in the note's ENML content. The en-media tag identifies the corresponding // Resource using the MD5 hash. string hashHex = BitConverter.ToString(hash).Replace("-", "").ToLower(); // The content of an Evernote note is represented using Evernote Markup Language // (ENML). The full ENML specification can be found in the Evernote API Overview // at http://dev.evernote.com/documentation/cloud/chapters/ENML.php note.Content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" + "<en-note>Here's the Evernote logo:<br/>" + "<en-media type=\"image/png\" hash=\"" + hashHex + "\"/>" + "</en-note>"; // Finally, send the new note to Evernote using the createNote method // The new Note object that is returned will contain server-generated // attributes such as the new note's unique GUID. Note createdNote = noteStore.createNote(authToken, note); Console.WriteLine(); Console.WriteLine("Successfully created new note with GUID: " + createdNote.Guid); Console.WriteLine(); // Share The Newly Created Note To Provide Access Using An Evernote URL // This Document Will Be Publicly Accessible. string noteKey = noteStore.shareNote(authToken, createdNote.Guid); Console.WriteLine(); Console.WriteLine("Successfully shared new note with Note Key: " + noteKey); Console.WriteLine(); // Twitter Integration try { // You Can Find Your SharedId By Sharing A Document On Your Evernote Sandbox Account // The Evernote Generated URL Will Contain This Value string sharedId = "s1"; string noteLink = "https://sandbox.evernote.com/shard/" + sharedId + "/sh/" + createdNote.Guid + "/" + noteKey; // You Will Need To Create A Twitter Developer Account For This Information. // All Of The Values Below Will Be Generated From Your Twitter Developer Account // Login In To Twitter And Use The Following URL: https://dev.twitter.com/apps // 1. Create Twitter Developer Account // 2. Create A New Application // 2. Set Access Level To Read and Write On The Application Page // 3. Generate Access Token At Bottom Of The Application Page OAuthTokens oaTokens = new OAuthTokens(); oaTokens.AccessToken = "Your Twitter Access Token Here"; oaTokens.AccessTokenSecret = "Your Twitter Access Token Secret Here"; oaTokens.ConsumerKey = "Your Twitter ConsumerKey Here"; oaTokens.ConsumerSecret = "Your Twitter ConsumerKey Here"; // Truncate Doc Title If It Is Longer Than 40 Characters string docTitle = createdNote.Title; if (docTitle.Length > 40) { docTitle.Substring(0, 40); } // Truncate Message If It Is Longer Than 140 Characters string message = "Evernote Doc - " + docTitle; if (message.Length > 140) { message = message.Substring(0, 140); } // Add URL To Tweet. Twitter Will Shorten If Neccessary message += " " + noteLink; // Update Twitter Status And Check Result For Success TwitterResponse<TwitterStatus> twStatus = TwitterStatus.Update(oaTokens, message); if (twStatus.Result.ToString().ToLower() != "success") { throw new Exception("Twitter Status Not Updated"); } Console.WriteLine(); Console.Write("Document Posted To Twitter"); Console.WriteLine(); } catch (Exception ex) { Console.Write(ex.ToString()); } Console.ReadLine(); }
public static byte[] TryCastByteArray(Bitmap bitmap) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(bitmap, typeof(byte[]))); }
//another easy way to convert image to bytearray public static byte[] imgToByteConverter(Image inImg) { ImageConverter imgCon = new ImageConverter(); return((byte[])imgCon.ConvertTo(inImg, typeof(byte[]))); }
public static byte[] ToByteArray(this Image image) { var converter = new ImageConverter(); return((byte[])converter.ConvertTo(image, typeof(byte[]))); }
private void Details_Load(object sender, EventArgs e) { ImageConverter converter = new ImageConverter(); pictureBox1.Image = (Image)converter.ConvertFrom(Image); }
public static byte[] ImageToByte(Image img) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(img, typeof(byte[]))); }
public static byte[] ConvertToEquirecTangular(Bitmap input, int outWidth, int outHeight) { Bitmap bitmap = new Bitmap(outWidth, outHeight, PixelFormat.Format24bppRgb); float u, v; float phi, theta; int cubeFaceWidth, cubeFaceHeight; cubeFaceWidth = input.Width / 4; cubeFaceHeight = input.Height / 3; for (int j = 0; j < bitmap.Height; j++) { v = 1 - ((float)j / bitmap.Height); theta = v * (float)Math.PI; for (int i = 0; i < bitmap.Width; i++) { u = ((float)i / bitmap.Width); phi = u * 2 * (float)Math.PI; float x, y, z; x = (float)Math.Sin(phi) * (float)Math.Sin(theta) * -1; y = (float)Math.Cos(theta); z = (float)Math.Cos(phi) * (float)Math.Sin(theta) * -1; float xa, ya, za; float a; a = Math.Max(Math.Abs(x), Math.Max(Math.Abs(y), Math.Abs(z))); xa = x / a; ya = y / a; za = z / a; Color color; int xPixel, yPixel; int xOffset, yOffset; if (xa == 1) { //Right xPixel = (int)((((za + 1f) / 2f) - 1f) * cubeFaceWidth); xOffset = 2 * cubeFaceWidth; //Offset yPixel = (int)((((ya + 1f) / 2f)) * cubeFaceHeight); yOffset = cubeFaceHeight; //Offset } else if (xa == -1) { //Left xPixel = (int)((((za + 1f) / 2f)) * cubeFaceWidth); xOffset = 0; yPixel = (int)((((ya + 1f) / 2f)) * cubeFaceHeight); yOffset = cubeFaceHeight; } else if (ya == 1) { //Up xPixel = (int)((((xa + 1f) / 2f)) * cubeFaceWidth); xOffset = cubeFaceWidth; yPixel = (int)((((za + 1f) / 2f) - 1f) * cubeFaceHeight); yOffset = 2 * cubeFaceHeight; } else if (ya == -1) { //Down xPixel = (int)((((xa + 1f) / 2f)) * cubeFaceWidth); xOffset = cubeFaceWidth; yPixel = (int)((((za + 1f) / 2f)) * cubeFaceHeight); yOffset = 0; } else if (za == 1) { //Front xPixel = (int)((((xa + 1f) / 2f)) * cubeFaceWidth); xOffset = cubeFaceWidth; yPixel = (int)((((ya + 1f) / 2f)) * cubeFaceHeight); yOffset = cubeFaceHeight; } else if (za == -1) { //Back xPixel = (int)((((xa + 1f) / 2f) - 1f) * cubeFaceWidth); xOffset = 3 * cubeFaceWidth; yPixel = (int)((((ya + 1f) / 2f)) * cubeFaceHeight); yOffset = cubeFaceHeight; } else { xPixel = 0; yPixel = 0; xOffset = 0; yOffset = 0; } xPixel = Math.Abs(xPixel); yPixel = Math.Abs(yPixel); xPixel += xOffset; yPixel += yOffset; if (yPixel == input.Height) { color = input.GetPixel(xPixel, yPixel - 1); } else { color = input.GetPixel(xPixel, yPixel); } bitmap.SetPixel(i, j, color); } } bitmap.Save("out.jpg", ImageFormat.Jpeg); ImageConverter imageConverter = new ImageConverter(); return((byte[])imageConverter.ConvertTo(bitmap, typeof(byte[]))); }
protected void btncompare_Click(object sender, EventArgs e) { try { //Reading Bytes From Uploaded Images if (FileUpload1.HasFile && FileUpload2.HasFile) { using (BinaryReader reader1 = new BinaryReader(FileUpload1.PostedFile.InputStream)) { using (BinaryReader reader2 = new BinaryReader(FileUpload2.PostedFile.InputStream)) { _barray1 = reader1.ReadBytes(FileUpload1.PostedFile.ContentLength); _barray2 = reader2.ReadBytes(FileUpload2.PostedFile.ContentLength); } } } //Converting Byte Array To Image And Then Into Bitmap ImageConverter ic = new ImageConverter(); Image img = (Image)ic.ConvertFrom(_barray1); Bitmap bmp1 = new Bitmap(img); Image img1 = (Image)ic.ConvertFrom(_barray2); Bitmap bmp2 = new Bitmap(img1); //Calling Compare Function if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciCompareOk) { Label1.Visible = true; Label1.Text = "Images Are Same"; } if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciPixelMismatch) { Label2.Visible = true; Label2.Text = "Pixel not Matching"; } if (Class1.Compare(bmp1, bmp2) == Class1.CompareResult.ciSizeMismatch) { Label3.Visible = true; Label3.Text = "Size is not Same"; } if (Class1.Compare(bmp1, bmp2) != Class1.CompareResult.ciCompareOk) { Label1.Visible=true; Label1.Text = "images are not same"; } if (Class1.Compare(bmp1, bmp2) != Class1.CompareResult.ciPixelMismatch ) { Label2.Visible = true; Label2.Text = "Pixel Matching"; } if (Class1.Compare(bmp1, bmp2) != Class1.CompareResult.ciSizeMismatch) { Label3.Visible = true; Label3.Text = "Size is Same"; } } catch (Exception ex) { Label1.Visible = true; Label1.Text = ex.Message.ToString(); } }
public async Task <Book> UpdateBookFromWeb_ORG(Book book, string addNotify = "") { Dictionary <string, string> corrections = BookCommonData.Corrections; book.Source = "ORG"; OnNotify($"Updating book {book.ClearTitle} from web (ORG) ..."); var web = new HtmlWeb(); var detailPage = await web.LoadFromWebAsync(book.Url); var detail = detailPage.DocumentNode.SelectSingleNode("//div[@class='book-detail']/dl"); if (detail == null) { OnNotify($"Error updating: the book {book.Title} page does not exist."); return(book); } var dtNodes = detail.SelectNodes("dt"); var ddNodes = detail.SelectNodes("dd"); for (var i = 0; i < dtNodes.Count; i++) { if (dtNodes[i].InnerText == "Year:") { book.Year = int.Parse(ddNodes[i].InnerText); } if (string.IsNullOrEmpty(book.Category) && dtNodes[i].InnerText == "Category:") { var _category = ""; foreach (var anode in ddNodes[i].SelectNodes("a")) { _category += anode.Attributes["href"].Value.Replace("http://www.allitebooks.org/", "").Replace("http://www.allitebooks.com/", "").TrimEnd('/') + ";"; } _category = _category.Substring(0, _category.Length - 1); foreach (var correction in corrections) { var key = correction.Key.Trim().Replace("*", ""); _category = _category.Replace(key, correction.Value.Trim()); } if (_category.Contains(";")) { _category = _category.Split(';')[0]; } book.Category = _category; } if (dtNodes[i].InnerText == "ISBN-10:") { book.ISBN = ddNodes[i].InnerText.Trim(); } if (dtNodes[i].InnerText == "Pages:") { book.Pages = int.Parse(ddNodes[i].InnerText); } if (dtNodes[i].InnerText.Contains("Author")) { book.Authors = ddNodes[i].InnerText?.Trim(); } } var img = detailPage.DocumentNode.SelectSingleNode("//div[@class='entry-body-thumbnail hover-thumb']/a/img").Attributes["src"].Value; try { using (var wc = new WebClient()) { byte[] data = wc.DownloadData(img); var bitmap = (Bitmap)((new ImageConverter()).ConvertFrom(data)); ImageConverter converter = new ImageConverter(); book.Cover = (byte[])converter.ConvertTo(bitmap, typeof(byte[])); } } catch { } var downloadLinks = detailPage.DocumentNode.SelectNodes("//span[@class='download-links']/a"); foreach (var node in downloadLinks) { var href = node.Attributes["href"].Value; if (href.Contains(".pdf")) { book.DownloadUrl = href; book.Extension = "pdf"; break; } else if (href.Contains(".epub")) { book.DownloadUrl = href; book.Extension = "epub"; } } return(book); }
protected void UploadLargeIconButton_Click(object sender, EventArgs e) { Util util = new Util(); Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID]; if (util.CheckSessionTimeout(State, Response, "../../Default.aspx")) return; if (UploadLargeIcon.UploadedFiles.Count > 0) { repeaterResultsLargeIcon.DataSource = UploadLargeIcon.UploadedFiles; repeaterResultsLargeIcon.DataBind(); repeaterResultsLargeIcon.Visible = true; string targetFolder = Server.MapPath(UploadLargeIcon.TargetFolder); foreach (UploadedFile file in UploadLargeIcon.UploadedFiles) { string name = file.GetName(); //file name and suffix if (!name.ToLower().EndsWith(".jpg")) { IconUploadMessage.Text = "File must be .jpg file"; return; } string file_path = targetFolder + @"\" + name; if (System.IO.File.Exists(file_path)) { byte[] image_data = File.ReadAllBytes(file_path); ImageConverter ic = new ImageConverter(); System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(image_data); Bitmap bitmap = new Bitmap(img); if (bitmap.Width != 512 || bitmap.Height != 512) { IconUploadMessage.Text = "The image '" + name + "' is not 512 X 512"; return; } string file_name = name.Replace(" ", "_"); util.SetApplicationLargeIcon(State, State["ApplicationID"].ToString(), bitmap, file_name, file_path); LargeIconButton.Visible = true; DeleteIcon.Visible = true; } } } else { repeaterResultsLargeIcon.Visible = false; IconUploadMessage.Text = "Browse for a file"; } }
//将Image变量转换成字节数组 public byte[] ConvertImageToByte(System.Drawing.Image img) { ImageConverter converter = new ImageConverter(); return((byte[])converter.ConvertTo(img, typeof(byte[]))); }
public static byte[] ImageToByte(System.Drawing.Image img) { ImageConverter converter = new ImageConverter(); return (byte[])converter.ConvertTo(img, typeof(byte[])); }
//YEARLY VIEW public async System.Threading.Tasks.Task <bool> DisplayYearlyViewAsync(Dictionary <String, int> menuItemCounter, Dictionary <DateTime, int> revenueCalendar, List <string> menuItemIds, Dictionary <DateTime, int> orderCount) { //String that will store the most popular item id string mostPopularMenuItemId; foreach (Order o in RealmManager.All <OrderList>().FirstOrDefault().orders) { //this will ignore all uncompleted orders if (o.time_completed == null) { continue; } //initalize this month and last month DateTime td = DateTime.Today; DateTime weekStart = new DateTime(td.Year, 1, 1, 0, 0, 0); DateTime orderTime = DateTime.ParseExact(o.time_completed.Replace('T', ' ').TrimEnd('Z'), "yyyy-MM-dd HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture);; //makeing it easier to key the revenue map by MONTH orderTime = new DateTime(orderTime.Year, orderTime.Month, 1, 0, 0, 0); //only added menuItems from orders for the current week if (DateTime.Compare(weekStart, orderTime) < 0) { //adding a key and setting it to 0 if it doesn't exist try { if (revenueCalendar[orderTime] == 0) { } } catch { orderCount[orderTime] = 0; revenueCalendar[orderTime] = 0; } //incrementing order count every order orderCount[orderTime] = orderCount[orderTime] + 1; foreach (OrderItem oi in o.menuItems) { menuItemIds.Add(oi._id); //add next menuitem id revenueCalendar[orderTime] = revenueCalendar[orderTime] + Convert.ToInt32(oi.price); //adding price of new menuitem } } } //updating menuItem map to see how often each was ordered foreach (string id in menuItemIds) { try { menuItemCounter[id] = menuItemCounter[id] + 1; } catch { continue; } } //finding the largest value and storing the key mostPopularMenuItemId = menuItemCounter.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; //Getting the most popular menuItem of the YEAR //this will only generate the charts once. After that the values you have been bound. if (yearlyDisplayed == false) { UxYearlyCharts(menuItemCounter, revenueCalendar, orderCount); yearlyDisplayed = true; } //finding in Realm, the most popular id MenuItem tempMenuItem = RealmManager.All <MenuItemList>().FirstOrDefault().menuItems.Where(x => x._id == mostPopularMenuItemId).FirstOrDefault(); YearlyPicture.Source = await ImageConverter.ConvertBase64ToImageSource(tempMenuItem.picture); YearlyTopItem.Text = tempMenuItem.name; //makeing the other grids hidden uxMonthlyViewGrid.Visibility = Visibility.Collapsed; uxWeeklyViewGrid.Visibility = Visibility.Collapsed; uxYearlyViewGrid.Visibility = Visibility.Visible; return(true); }