Пример #1
0
 private void Check()
 {
     PKDataContext pkdata = new PKDataContext(clsDeclare.gblConnectStringLinQ);
     byte[] arrImgFront = null;
     byte[] arrImgBack = null;
     frontPic.EditValue = null;
     backPic.EditValue = null;
     ImageConverter converter = new ImageConverter();
     var pk = new Execute(pkdata).GetSinglePKIn(txtRFID.Text);
     if (pk != null)
     {
         new Execute(pkdata).getImage(pk.ID, ref arrImgFront, true);
         if (arrImgFront != null)
         {
             Image tmp = (Image)converter.ConvertFrom(arrImgFront);
             frontPic.Image = tmp;
             arrImgFront = null;
         }
         new Execute(pkdata).getImage(pk.ID, ref arrImgBack, false);
         if (arrImgBack != null)
         {
             Image tmp = (Image)converter.ConvertFrom(arrImgBack);
             backPic.Image = tmp;
             arrImgBack = null;
         }
         LoadDataToControl(pk);
         btnOK.Focus();
     }
 }
Пример #2
0
        public static Image byteArrayToImage(byte[] byteArrayIn)
        {
            ImageConverter imageConverter = new System.Drawing.ImageConverter();
            Image          image          = imageConverter.ConvertFrom(byteArrayIn) as Image;

            return(image);
        }
        //LOGO lấy từ FrameworkParams.ReportHeaderImage
        public CompanyInfoHeaderStartTitleGridEndFooter()
        {
            CompanyInfo info = DACompanyInfo.Instance.load();

            //Lấy logo
            ImageConverter ic = new ImageConverter();
            Image img = (Image)ic.ConvertFrom(info.logo);

            ImageCollection images = new ImageCollection();
            images.ImageSize = new Size(48, 48);
            images.AddImage(img);

            ReportHeaderImage = images.Images[0];

            //Lay Info
            String blank = "                      ";
            StringBuilder str = new StringBuilder("");

            if (info.name != null) str.AppendLine(blank + info.name);
            if (info.address != null) str.AppendLine(blank + "Địa chỉ: " + info.address);
            if (info.phone != null) str.Append(blank + "Điện thoại: " + info.phone);
            if (info.fax != null) str.Append("   Fax: " + info.fax);
            str.AppendLine();
            if (info.email != null) str.Append(blank + "Email: " + info.email);
            if (info.website != null) str.Append("   Website: " + info.website);

            RichTextBox r = new RichTextBox();
            r.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            r.Text = str.ToString();
            rtfGridHeader = r.Rtf;
        }
Пример #4
0
		protected Image GetPhoto() {
			if((photo == null) && (Photo_Binary != null)) {
				ImageConverter imageConverter = new ImageConverter();
				photo = (Image)imageConverter.ConvertFrom(Photo_Binary);
			}
			return photo;
		}
Пример #5
0
    /// <summary>
    /// 根据查询语句从数据库中读取多个文件流,并返回一个图片数组,出错返回null
    /// </summary>
    internal System.Drawing.Image[] ReadFileToImageArr(string sql)
    {
        try
        {
            DataTable dt = this.DBTable(sql, null, null);
            if (dt == null || dt.Rows.Count == 0)
            {
                return(null);
            }

            System.Drawing.ImageConverter imgC = new System.Drawing.ImageConverter();//将byte[]转换成图片
            Image[] imgArr = new Image[dt.Rows.Count];

            for (int j = 0; j < imgArr.Length; j++)
            {
                byte[] bFile = (byte[])dt.Rows[j][0];
                bFile = this.ReduceByteArr(bFile);//解密

                imgArr[j] = (Image)imgC.ConvertFrom(bFile);
            }

            return(imgArr);
        }
        catch
        {
            return(null);
        }
    }
Пример #6
0
    protected override void OnPreRender(EventArgs e)
    {
        //throw new Exception(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]));
        Response.Clear();
        Response.ContentType = "image/jpeg";
        WebClient webclient = new WebClient();

        webclient.Headers.Clear();
        webclient.Headers.Add("Accept: image/jpeg, application/x-ms-application, image/gif, image/png, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");
        //webclient.Headers.Add("Accept-Encoding: gzip, deflate");
        webclient.Headers.Add("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)");

        byte[] data = webclient.DownloadData(DES.Decrypt(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]), shTwiX.shFunctions.key));
        do
        {
        } while (webclient.IsBusy);
        ImageConverter imageConverter = new System.Drawing.ImageConverter();

        try
        {
            System.Drawing.Image image = (System.Drawing.Image)imageConverter.ConvertFrom(data);
            image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch
        {
            Response.Write(data.Length.ToString() + "<br/>" + Request.QueryString[0]);
        }
    }
Пример #7
0
        static void Main()
        {
            SqlConnection con = new SqlConnection(Settings.Default.NortwindConStr);
            con.Open();
            using (con)
            {
                Console.WriteLine("Retriving images from DB and saving to computer...");
                SqlCommand comand = new SqlCommand("SELECT Picture, CategoryId FROM Categories", con);
                SqlDataReader reader = comand.ExecuteReader();
                while (reader.Read())
                {
                    byte[] photo = (byte[])reader[0];
                    MemoryStream ms = new MemoryStream(photo);
                    int id = (int)reader[1];
                       
                    ms.Close();
                    ImageConverter imgConverter = new ImageConverter();

                    Image img = imgConverter.ConvertFrom(photo) as Image;
                    
                    
                    img.Save(id + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);


                  
                 
                }
                Console.WriteLine("Done.");
            }
        }
        private Image byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            Image img = (Image)converter.ConvertFrom(byteArrayIn);

            return img;
        }
Пример #9
0
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            Image img = (Image)converter.ConvertFrom(byteArrayIn);

            return(img);
        }
Пример #10
0
            /// <summary>
            /// Convert Tiff image to another mime-type bitmap
            /// </summary>
            /// <param name="tiffImage">Source TIFF file</param>
            /// <param name="mimeType">Desired result mime-type</param>
            /// <returns>Converted image</returns>
            public Bitmap ConvertTiffToBitmap(Image tiffImage, string mimeType)
            {
                var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == "image/tiff");

                if (imageCodecInfo == null)
                {
                    return null;
                }
                Bitmap sourceImg;

                using (var memoryStream = new MemoryStream())
                {
                    // Setting encode params
                    var imageEncoderParams = new EncoderParameters(1);
                    imageEncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    tiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams);
                    tiffImage.Dispose();

                    var ic = new ImageConverter();

                    // Reading stream data to new image
                    var tempTiffImage = (Image)ic.ConvertFrom(memoryStream.GetBuffer());

                    // Setting new result mime-type
                    imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == mimeType);
                    if (tempTiffImage != null) tempTiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams);

                    sourceImg = new Bitmap(Image.FromStream(memoryStream, true));

                }

                return sourceImg;
            }
 public Bitmap convert_ByteArrayToBitmap(byte[,] byteArray)
 {
     ImageConverter ic = new ImageConverter();
     Image img = (Image)ic.ConvertFrom(byteArray);
     Bitmap bitmap1 = new Bitmap(img);
     return bitmap1;
 }
Пример #12
0
        /// <summary>
        /// convert byte[] to an image
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private static System.Drawing.Image byteArrayToImage(byte[] b)
        {
            ImageConverter imgconv = new System.Drawing.ImageConverter();

            System.Drawing.Image img = (System.Drawing.Image)imgconv.ConvertFrom(b);
            return(img);
        }
 /// <summary>
 /// Converte um array de bytes em um bitmap
 /// </summary>
 /// <param name="instance">Objeto a ser convertido</param>
 /// <returns>Bitmap convertido</returns>
 public static Bitmap ToBitmap(this byte[] instance)
 {
     ImageConverter ic = new ImageConverter();
     System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(instance);
     Bitmap bitmap = new Bitmap(img);
     return bitmap;
 }
Пример #14
0
    protected override void OnPreRender(EventArgs e)
    {
        //throw new Exception(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]));
        Response.Clear();
        Response.ContentType = "image/jpeg";
        WebClient webclient = new WebClient();
        webclient.Headers.Clear();
        webclient.Headers.Add("Accept: image/jpeg, application/x-ms-application, image/gif, image/png, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");
        //webclient.Headers.Add("Accept-Encoding: gzip, deflate");
        webclient.Headers.Add("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)");

        byte[] data = webclient.DownloadData(DES.Decrypt(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]), shTwiX.shFunctions.key));
        do
        {
        } while (webclient.IsBusy);
        ImageConverter imageConverter = new System.Drawing.ImageConverter();
        try
        {
            System.Drawing.Image image = (System.Drawing.Image)imageConverter.ConvertFrom(data);
            image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch
        {
            Response.Write(data.Length.ToString() + "<br/>" + Request.QueryString[0]);
        }
    }
Пример #15
0
 public static Image ImageFromStr(string strImageData)
 {
     if (strImageData == "")
         return null;
     byte[] byteImageData = new Byte[0];
     byteImageData = Convert.FromBase64String(strImageData);
     ImageConverter ic = new ImageConverter();
     Image img = (Image)ic.ConvertFrom(byteImageData);
     return img;
 }
Пример #16
0
        private static GDI.Image GetGdiImageFromBytes(byte[] gdiImageBytes)
        {
            if (gdiImageBytes == null)
            {
                throw new ArgumentNullException(nameof(gdiImageBytes));
            }

            var converter = new GDI.ImageConverter();

            return((GDI.Image)converter.ConvertFrom(gdiImageBytes));
        }
Пример #17
0
 public Image byteArrayToImage(byte[] byteArrayIn)
 {
     try
     {
         ImageConverter imageConverter = new System.Drawing.ImageConverter();
         Image          image          = imageConverter.ConvertFrom(byteArrayIn) as Image;
         return(image);
     }
     catch (Exception) { }
     return(null);
 }
        //---------------------------------------------------------------------
        /// <summary>
        /// Converts a Base64-String to an Image
        /// </summary>
        /// <param name="base64String">
        /// String to convert
        /// </param>
        /// <returns>
        /// Image created from the String
        /// </returns>
        public static Image GetImageFromString(string base64String)
        {
            byte[] buffer = Convert.FromBase64String(base64String);

            if (buffer != null)
            {
                ImageConverter ic = new ImageConverter();
                return ic.ConvertFrom(buffer) as Image;
            }
            else
                return null;
        }
Пример #19
0
        public void ResourceRepoFetches()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Bitmap>(b => ic.ConvertFrom(b) as Bitmap, s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var luna = repo.Fetch("Luna_DIFF");

                Assert.IsNotNull(luna);
            }
        }
 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;
 }
        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            textBox2.Text     = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
            textBox3.Text     = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
            textBox4.Text     = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
            richTextBox1.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
            byte[] bytes = (byte[])dataGridView1.SelectedRows[0].Cells[3].Value;
            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            Image img = (Image)converter.ConvertFrom(bytes);

            pictureBox1.Image = img;
            button1.Enabled   = true;
            button3.Enabled   = true;
        }
Пример #22
0
        private void ItemsDataGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                if (ItemsDataGridView.CurrentCell != null && currentRow != ItemsDataGridView.CurrentCell.RowIndex)
                {
                    currentRow           = ItemsDataGridView.CurrentCell.RowIndex;
                    ItemNewName_txt.Text = ItemsDataGridView.Rows[currentRow].Cells["CODE"].Value.ToString();
                    //ItemName_txt.Text = ItemsDataGridView.Rows[currentRow].Cells["CODE"].Value.ToString();
                    ItemModel_txt.Text    = ItemsDataGridView.Rows[currentRow].Cells["MODEL"].Value.ToString();
                    ItemQuantity_txt.Text = ItemsDataGridView.Rows[currentRow].Cells["QTY_BOX"].Value.ToString();
                    ItemPrice_txt.Text    = ItemsDataGridView.Rows[currentRow].Cells["PRICE"].Value.ToString();
                    ItemCategory_txt.Text = ItemsDataGridView.Rows[currentRow].Cells["CATEGORYNAME"].Value.ToString();
                    TQUANTITY_txt.Text    = ItemsDataGridView.Rows[currentRow].Cells["T_QUANTITY"].Value.ToString();
                    byte[] byteBLOBData = (byte[])ItemsDataGridView.Rows[currentRow].Cells["IMAGE"].Value;

                    System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                    Image img = (Image)converter.ConvertFrom(byteBLOBData);


                    MemoryStream ms = new MemoryStream(byteBLOBData);
                    ms.Write(byteBLOBData, 0, byteBLOBData.Length);
                    ms.Position          = 0; // THIS !!!!!
                    ItemPictureBox.Image = Image.FromStream(ms, true);



                    //byte[] imgData = (byte[])ItemsDataGridView.Rows[currentRow].Cells[5].Value;
                    //MemoryStream ms = new MemoryStream(imgData);
                    //ms.Seek(0, SeekOrigin.Begin);
                    //Bitmap bmp = new Bitmap(ms);
                    //ItemPictureBox.Image = Image.FromStream(ms);


                    //Bitmap IMG = new Bitmap(ItemPictureBox.Image);
                    //MemoryStream stream = new MemoryStream();
                    //IMG.
                    //IMG.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

//                    Bitmap image = new Bitmap();
//                    ItemPictureBox.Image =
                }
            }
            catch (Exception ex)
            {
                Variables.NotificationStatus       = true;
                Variables.NotificationMessageTitle = this.Name;
                Variables.NotificationMessageText  = ex.Message.ToString();
            }
        }
Пример #23
0
        internal void FirstRunSetup()
        {
            // Timing rig
            Debug.WriteLine("[INFO] Beginning first-run initialization.");
            Stopwatch timer = new Stopwatch();
            timer.Start();

            // Function start
            dbEngine.createDbFile(); // First run -- DB file will be needed

            ASComicAccess.xkcd.ComicMetadata meta = accessEngine.getComic();
            string imgPath = meta.img;

            // Download the image file
            WebClient connectAgent = new WebClient();
            ImageConverter converter = new ImageConverter();
            byte[] rawData;

            try
            {
                rawData = connectAgent.DownloadData(imgPath);
            }
            catch (WebException)
            {
                Debug.WriteLine("[ERROR] WebException thrown - Not connected?");
                return;
            }

            Image img;
            try
            {
                img = (Image)converter.ConvertFrom(rawData);
            }
            catch
            {
                Debug.Fail("[ERROR] Error thrown in image parser");
                throw;
            }

            dbEngine.insertRow(meta);

            if (xkcd_Viewer.Properties.Settings.Default.offlineMode)
                dbEngine.updateImgData(int.Parse(meta.num), img);

            // Function end; stop timer rig
            timer.Stop();
            timerResult = timer.ElapsedMilliseconds;
            Debug.WriteLine("[INFO] Completed first-run initialization in " + timerResult + "ms");
        }
Пример #24
0
    /// <summary>
    /// 根据查询语句从数据库中读取一个文件流,并返回一张图片,出错返回null
    /// </summary>
    public System.Drawing.Image ReadFileToImage(string sql)
    {
        DataTable dt = this.DBTable(sql, null, null);

        if (dt == null || dt.Rows.Count == 0)
        {
            return(null);
        }

        byte[] bFile = (byte[])dt.Rows[0][0];
        bFile = this.ReduceByteArr(bFile);                                        //解密

        System.Drawing.ImageConverter imgC = new System.Drawing.ImageConverter(); //将byte[]转换成图片
        System.Drawing.Image          img  = (Image)imgC.ConvertFrom(bFile);
        return(img);
    }
Пример #25
0
 private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
 {
     try
     {
         textBox1.Text     = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
         textBox2.Text     = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
         richTextBox1.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
         byte[] bytes = (byte[])dataGridView1.SelectedRows[0].Cells[3].Value;
         System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
         Image img = (Image)converter.ConvertFrom(bytes);
         pictureBox1.Image = img;
         cid = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
     }
     catch (Exception)
     {
         MessageBox.Show("Please select candidate properly.");
     }
 }
Пример #26
0
		private async void btnConnect_Click( object sender, EventArgs e )
		{
			this.btnConnect.Enabled = false;
			this.btnCancel.Enabled = true;
			this.pbStatus.Visible = true;

			Camera c = new Camera( this.txtHostName.Text, Int32.Parse(this.txtPort.Text), this.txtUserName.Text, this.txtPassword.Text );

			this.lblStatus.Text = "Getting port information...";
			GetPortInfoResult ports = await c.GetPortInfoAsync( this.cts.Token );
			this.lblHttpPort.Text = ports.HttpPort.ToString( CultureInfo.InvariantCulture );
			this.lblHttpsPort.Text = ports.HttpsPort.ToString( CultureInfo.InvariantCulture );
			this.lblMediaPort.Text = ports.MediaPort.ToString( CultureInfo.InvariantCulture );
			this.lblOnvifPort.Text = ports.OnvifPort.ToString( CultureInfo.InvariantCulture );

			this.lblStatus.Text = "Getting IP information...";
			GetIPInfoResult ipInfo = await c.GetIPInfoAsync( this.cts.Token );

			this.lblStatus.Text = "Getting model name...";
			GetProductModelNameResult productModelName = await c.GetProductModelNameAsync( this.cts.Token );
			this.lblCameraInfo.Text = String.Format( CultureInfo.InvariantCulture, "Model {0} on {1}", productModelName.ModelName, ipInfo.IPAddress);

			this.lblStatus.Text = "Getting device information...";
			GetDeviceInfoResult deviceInfo = await c.GetDeviceInfoAsync( this.cts.Token );
			this.lblProductName.Text = deviceInfo.ProductName;
			this.lblDeviceName.Text = deviceInfo.DeviceName;
			this.lblSerialNo.Text = deviceInfo.SerialNumber;
			this.lblMac.Text = deviceInfo.MacAddress;
			this.lblCurrentDate.Text = deviceInfo.CurrentDate.ToString(CultureInfo.CurrentCulture);
			this.lblTimeZone.Text = deviceInfo.TimeZone;
			this.lblFirmwareVersion.Text = deviceInfo.FirmwareVersion;
			this.lblHardwareVersion.Text = deviceInfo.HardwareVersion;

			this.lblStatus.Text = "Getting snapshot image...";
			GetSnapshotResult snapshot = await c.GetSnapshotAsync( this.cts.Token );
			ImageConverter converter = new ImageConverter();
			this.pbSnapshot.Image = (Image) converter.ConvertFrom( snapshot.Image );

			this.lblStatus.Text = "Ready.";
			this.pbStatus.Visible = false;
			this.btnConnect.Enabled = true;
			this.btnCancel.Enabled = false;
		}
Пример #27
0
        public static Bitmap GetPic(string url)
        {
            Bitmap pic = null;
            try
            {
                ImageConverter ic = new ImageConverter();

                using (WebClient Client = new WebClient())
                {
                    byte[] data = Client.DownloadData(url);
                    pic = (Bitmap)ic.ConvertFrom(data);
                }
            }
            catch (Exception)
            {

            }

            return pic;
        }
Пример #28
0
        public void ResourceRepoEnumerates()
        {
            var ic = new ImageConverter();

            using (var repo = new ResourceWrapper<Bitmap>(b => ic.ConvertFrom(b) as Bitmap, s => null, n => null, testRes.ResourceManager))
            {
                Assert.AreEqual(8, repo.Length);

                var bitmaps = repo.Where(s => s.Value != null).Select(s => s.Value).OfType<Bitmap>();

                Assert.AreEqual(4, bitmaps.Count());

                var en = repo.GetEnumerator();

                if (en.MoveNext())
                {
                    Assert.IsNotNull(en.Current);
                    en.Reset();
                }
            }
        }
Пример #29
0
        public static void Main()
        {
            Console.WriteLine("Retrieving data...");
            var connectionString = "Server=(local); Database=Northwind; Integrated Security=true;";
            var connection = new SqlConnection(connectionString);
            connection.Open();
            var command = new SqlCommand(cmdText: "select CategoryName, Picture from Categories", connection: connection);
            var converter = new ImageConverter();
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                var bitmap = (byte[])reader["Picture"];
                string name = ((string)reader["CategoryName"]).Split('/')[0].ToLower();
                var image = (Image)converter.ConvertFrom(bitmap);
                image.Save($"../../Images/{name}.jpeg", ImageFormat.Jpeg);
            }

            connection.Close();

            Console.WriteLine("Data saved to disk.");
        }
Пример #30
0
        //Chuyển chuỗi byte lấy từ database trở lại thành hình ảnh
        private Image byteArrayToImage(byte[] byteArrayIn)
        {
            try
            {
                //MemoryStream ms = new MemoryStream(byteArrayIn);
                //Image returnImage = Image.FromStream(ms);
                ImageConverter imageConverter = new System.Drawing.ImageConverter();
                Image          image          = imageConverter.ConvertFrom(byteArrayIn) as Image;
                return(image);

                //using (var ms = new MemoryStream(byteArrayIn))
                //{
                //    return Image.FromStream(ms);
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Thông báo");
            }
            return(null);
        }
Пример #31
0
 public IEnumerable<CoverImage> GetCoverImagesFrom(string mediaFilePath)
 {
     // to save into tag, see: http://forums.codeguru.com/showthread.php?506806-TagLib-Writing-Images-to-File
     var tagLibFile = TagLibFile.Create(mediaFilePath);
     var ic = new ImageConverter();
     var iNumberOfPictures = tagLibFile.Tag.Pictures.Length;
     for (var i = 0; i < iNumberOfPictures; i++)
     {
         var picture = tagLibFile.Tag.Pictures[i];
         var image = (Image)ic.ConvertFrom(picture.Data.Data);
         yield return new CoverImage
         {
             ImageData = image,
             Type = picture.Type,
             IsAcceptableSize = ImageIsOfAcceptableSize(image.Width, image.Height),
             FileExtension = GetFileExtensionFor(image),
             CheckSum = picture.Data.Checksum
         };
     }
     tagLibFile.Dispose();
 }
Пример #32
0
 private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
 {
     try
     {
         textBox2.Text        = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
         dateTimePicker1.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
         byte[] bytes = (byte[])dataGridView1.SelectedRows[0].Cells[3].Value;
         System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
         Image img = (Image)converter.ConvertFrom(bytes);
         pictureBox1.Image     = img;
         dataGridView1.Enabled = false;
         textBox3.Text         = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
         button3.Enabled       = true;
         textBox1.Enabled      = false;
         button1.Enabled       = true;
     }
     catch (Exception)
     {
         MessageBox.Show("Please select election properly.");
     }
 }
Пример #33
0
        public void SaveLogoData(byte[] logo)
        {
            UserProfileLogo userProfileLogo = _serviceHubEntities.UserProfileLogos.SingleOrDefault(o => o.AspNetUserId == _aspNetUserId);
            if (userProfileLogo == null)
            {
                userProfileLogo = new UserProfileLogo();
                _serviceHubEntities.UserProfileLogos.Add(userProfileLogo);
                userProfileLogo.AspNetUserId = _aspNetUserId;
            }

            ImageConverter imageConverter = new ImageConverter();
            using (Image img = (Image)imageConverter.ConvertFrom(logo))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    ImageResizer imageResizer = new ImageResizer(300, 300, 70);
                    imageResizer.ResizeImage(img, memoryStream);
                    userProfileLogo.LogoData = memoryStream.ToArray();
                }
            }
        }
Пример #34
0
        public static Bitmap GetResultImage(Model model)
        {
            string fontPath = @"E:\xWork\Apps\Work\AddTextToImage\AddTextToImage.WebUI\fonts\";

            IRepository<TextTemplate> _textTemplateRepository = new Repository<TextTemplate>(new DbContextFactory());
            IRepository<ClipartTemplate> _clipartTemplateRepository = new Repository<ClipartTemplate>(new DbContextFactory());

            if (model == null)
                return null; //ToDo

            ImageConverter ic = new ImageConverter();
            Image img = (Image)ic.ConvertFrom(model.Image);
            Bitmap bmpResult = new Bitmap(img);

            Graphics graphics = Graphics.FromImage(bmpResult);

            foreach (var modelItem in model.Items)
            {
                TemplateBase template = null;

                if (modelItem.ItemType == 0)
                {
                    template = _textTemplateRepository.GetAllWithInclude("Font").Where(p => p.Id == modelItem.TemplateId).FirstOrDefault();
                }
                else
                {
                    template = _clipartTemplateRepository.GetAllWithInclude("Font").Where(p => p.Id == modelItem.TemplateId).FirstOrDefault();
                }

                OutlineTextProcessor outlineTextProcessor = new OutlineTextProcessor(modelItem, template, fontPath);
                Bitmap image = outlineTextProcessor.GetImage();

                graphics.DrawImage((Image)image, new Point(modelItem.PositionLeft, modelItem.PositionTop));
            }

            graphics.Flush();
            graphics.Dispose();

            return bmpResult;
        }
Пример #35
0
        //ToDo -
        private void ModelToSampleForm_Load(object sender, EventArgs e)
        {
            string fontPath = @"E:\xWork\Apps\Work\AddTextToImage\AddTextToImage.WebUI\fonts\";

            model = _modelRepository.Get(ModelId);

            if (model != null)
            {
                ImageConverter ic = new ImageConverter();
                Image img = (Image)ic.ConvertFrom(model.Image);
                Bitmap bmpResult = new Bitmap(img);

                Graphics graphics = Graphics.FromImage(bmpResult);

                foreach (var modelItem in model.Items)
                {
                    TemplateBase template = null;

                    if (modelItem.ItemType == 0)
                    {
                        template = _textTemplateRepository.GetAllWithInclude("Font").Where(p => p.Id == modelItem.TemplateId).FirstOrDefault();
                    }
                    else
                    {
                        template = _clipartTemplateRepository.GetAllWithInclude("Font").Where(p => p.Id == modelItem.TemplateId).FirstOrDefault();
                    }

                    OutlineTextProcessor outlineTextProcessor = new OutlineTextProcessor(modelItem, template, fontPath);
                    Bitmap image = outlineTextProcessor.GetImage();

                    graphics.DrawImage((Image)image, new Point(modelItem.PositionLeft, modelItem.PositionTop));
                }

                resultImage = bmpResult;

                graphics.Flush();
                graphics.Dispose();
            }
        }
        private static Image TextToImage(string newData)
        {
            Image _return = AMTANGEE.SDK.Resources.Images[SDK.Resources.ImageIndexes.Website];

            try
            {
                if (newData.Length > 0)
                {
                    byte[] byteumrechner = Convert.FromBase64String(newData);
                    if (byteumrechner != null && byteumrechner.Length > 0)
                    {
                        var _with2 = new System.Drawing.ImageConverter();
                        _return = (Image)_with2.ConvertFrom(byteumrechner);
                    }
                }
            }
            catch
            {
                _return = null;
            }
            return(_return);
        }
Пример #37
0
        public void Execute()
        {
            //
            // Imageオブジェクトを取得.
            //
            var image = GDIImage.FromFile("resources/database.png");

            //
            // Imageをバイト配列に変換.
            //   Imageから別のオブジェクトに変換する場合はConvertToを利用する.
            //
            var converter = new ImageConverter();
            var imageBytes = (byte[]) converter.ConvertTo(image, typeof(byte[]));

            //
            // バイト配列をImageに変換.
            //   バイト配列からImageオブジェクトに変換する場合はConvertFromを利用する.
            //
            var image2 = (GDIImage) converter.ConvertFrom(imageBytes);

            // 確認.
            Debug.Assert(image != null);
            Debug.Assert((imageBytes != null) && (imageBytes.Length > 0));
            Debug.Assert(image2 != null);

            //
            // [補足]
            // Imageオブジェクトをファイルとして保存する場合は以下のようにする.
            //
            //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //string fileName    = @"Sample.png";
            //string filePath    = Path.Combine(desktopPath, fileName);
            //
            //using (Stream stream = File.Create(filePath))
            //{
            //  image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
            //}
        }
Пример #38
0
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            using (Stream stream = new MemoryStream(byteArrayIn))
            {
                //stream.Write(byteArrayIn, 0, byteArrayIn.Length);
                //return System.Drawing.Bitmap.FromStream(stream, true);
                ImageConverter image  = new System.Drawing.ImageConverter();
                Image          image2 = image.ConvertFrom(byteArrayIn) as Image;
                return(image2);
                //hasilgambar.Image = image2;
            }

            // byteArrayIn = new byte[200 * 200 * 3];
            MemoryStream ms = new System.IO.MemoryStream(byteArrayIn);
            //ms.Seek(0, SeekOrigin.Begin);
            //Image newImage = System.Drawing.Image.FromStream(ms);
            Image returnImage = Image.FromStream(ms);

            return(returnImage);
            //Bitmap bmp = new Bitmap(ms);
            //return new Bitmap(bmp);
            //hasilgambar.Image = newImage;
        }
Пример #39
0
        private void frmCatalog_Load(object sender, EventArgs e)
        {
            // Align UnitPrice to right
            this.dgProducts.Columns["UnitPrice"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            // Load products information
            string[,] products = salesForm.getMyBusiness().getProductsInformation();
            int count = products.GetLength(0);

            for (int i = 0; i < count; i++)
            {
                int n = dgProducts.Rows.Add();
                ImageConverter ic = new ImageConverter();
                Image img = (Image)ic.ConvertFrom(salesForm.getMyBusiness().getPictureByID(int.Parse(products[i, 2])));
                Bitmap bitmap1 = new Bitmap(img);
                dgProducts.Rows[n].Cells[0].Value = img; // Show category picture on first column

                //dgProducts.Rows[n].Cells[0].Value = products[i, 4];
                dgProducts.Rows[n].Cells[1].Value = products[i, 0];
                dgProducts.Rows[n].Cells[2].Value = products[i, 1];
                dgProducts.Rows[n].Cells[3].Value = products[i, 3];
                dgProducts.Rows[n].Cells[4].Value = products[i, 2];
            }
        }
Пример #40
0
 internal static Bitmap GetBitmap(byte[] array)
 {
     ImageConverter ic = new ImageConverter();
     System.Drawing.Image pic = (System.Drawing.Image)ic.ConvertFrom(array);
     return new Bitmap(pic);
 }
Пример #41
0
        private void LoadQuestion(Question question, string choices)
        {
            buttonSubmit.Enabled = false;
            buttonNext.Enabled   = false;
            buttonBack.Enabled   = false;

            this.buttonCancel.Text = "Close";

            //Clear form
            flowLayoutPanelQuestion.Controls.Clear();
            flowLayoutPanelAnswers.Controls.Clear();

            //generating question
            TextBox txtQuestion = new TextBox();

            txtQuestion.ScrollBars = ScrollBars.Both;
            txtQuestion.Multiline  = true;


            PictureBox pBox = new PictureBox();

            pBox.Width  = flowLayoutPanelQuestion.Width;
            pBox.Height = flowLayoutPanelQuestion.Height;


            if (question.question.Contains(" *** ")) // there is an image in the question
            {
                int imageStartindex = question.question.IndexOf(" *** ");
                int imageEndIndex   = question.question.LastIndexOf(" *** ");

                txtQuestion.Text   = question.Id + " - " + question.question.Remove(imageStartindex, imageEndIndex - imageStartindex);
                txtQuestion.Width  = flowLayoutPanelQuestion.Width;
                txtQuestion.Height = Convert.ToInt32(flowLayoutPanelQuestion.Height * 0.25);
                //inserting text to the form
                flowLayoutPanelQuestion.Controls.Add(txtQuestion);

                byte[] bImage = Convert.FromBase64String(question.question.Substring(imageStartindex, imageEndIndex - imageStartindex).Replace(" *** ", ""));

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                pBox.Image  = (Image)converter.ConvertFrom(bImage);
                pBox.Width  = flowLayoutPanelQuestion.Width;
                pBox.Height = Convert.ToInt32(flowLayoutPanelQuestion.Height * 0.75);
                //inserting image to the form
                flowLayoutPanelQuestion.Controls.Add(pBox);
            }
            else
            {
                txtQuestion.Text   = question.Id + " - " + question.question;
                txtQuestion.Width  = flowLayoutPanelQuestion.Width;
                txtQuestion.Height = flowLayoutPanelQuestion.Height;

                //inserting to the form
                flowLayoutPanelQuestion.Controls.Add(txtQuestion);
            }

            //answers are generating
            if (question.allowMultipleSelect)
            {
                //use check box control
                foreach (MyExamForm.Choice choice in question.choices)
                {
                    if (choiceIds.Contains(choice.Id))
                    {
                        flowLayoutPanelAnswers.Controls.Add(new CheckBox()
                        {
                            Text = choice.answerText, Name = choice.Id + "-" + choice.isCorrect, Width = flowLayoutPanelAnswers.Width, Checked = true
                        });
                    }
                    else
                    {
                        flowLayoutPanelAnswers.Controls.Add(new CheckBox()
                        {
                            Text = choice.answerText, Name = choice.Id + "-" + choice.isCorrect, Width = flowLayoutPanelAnswers.Width
                        });
                    }
                }
            }
            else
            {
                //use radio control
                foreach (MyExamForm.Choice choice in question.choices)
                {
                    if (choiceIds.Contains(choice.Id))
                    {
                        flowLayoutPanelAnswers.Controls.Add(new RadioButton()
                        {
                            Text = choice.answerText, Name = choice.Id + "-" + choice.isCorrect, Width = flowLayoutPanelAnswers.Width, Checked = true
                        });
                    }
                    else
                    {
                        flowLayoutPanelAnswers.Controls.Add(new RadioButton()
                        {
                            Text = choice.answerText, Name = choice.Id + "-" + choice.isCorrect, Width = flowLayoutPanelAnswers.Width
                        });
                    }
                }
            }
        }
Пример #42
0
        private void showTrackInfo()
        {
            bool groupMode = string.IsNullOrEmpty(currentJob[Fields.Path].ToString());
            string path = groupMode ? ((List<String>)currentJob[Fields.PathList])[0] : currentJob[Fields.Path].ToString();

            txtQuery.Text = jCon.CreateQueryString(int.Parse(currentJob[Fields.ID].ToString()));
            gridCurrentJob.Rows.Clear();
            gridCurrentJob.Rows.Add(Verbal.JobIndex, (int)currentJob[Fields.ID]);
            gridCurrentJob.Rows.Add(Verbal.DoneTotalJobs, jCon.CompletedJobsCount + "/" + jCon.JobsCount);
            gridCurrentJob.Rows.Add(Fields.Path,  groupMode ? Verbal.GroupingPath : path);
            gridCurrentJob.Rows.Add(Verbal.Track, groupMode ? Verbal.GroupingTitles : currentJob[Fields.Title].ToString());
            gridCurrentJob.Rows.Add(Fields.Artist, currentJob[Fields.Artist].ToString());
            gridCurrentJob.Rows.Add(Fields.Album, currentJob[Fields.Album].ToString());

            if (groupMode)
            {
                gridCurrentJob.Rows.Add(
                    Verbal.Warning,
                    string.Format(Verbal.ArtAppliesCount, ((List<String>)currentJob[Fields.PathList]).Count)
                );
            }

            var track = TagLib.File.Create(path);
            gridCurrentJob.Rows.Add(Verbal.ArtInFile, track.Tag.Pictures.GetLength(0));
            if (track.Tag.Pictures.GetLength(0) > 0)
            {
                var ic = new ImageConverter();
                Image i = null;
                try
                {
                    cellEmbeded.Thumbnail = cellEmbeded.FullSize = i = (Image)ic.ConvertFrom(track.Tag.Pictures[0].Data.Data);
                }
                catch(ArgumentException e) { } // Supress strange mime-formats, that Image Converter can't handle
                if (i != null)
                {
                    cellEmbeded.Caption = string.Format(
                        "{0}; {1}x{2}px",
                        Verbal.Embedded,
                        cellEmbeded.FullSize.Width,
                        cellEmbeded.FullSize.Height
                    );
                }
            }
            else
            {
                cellEmbeded.Thumbnail = Properties.Resources.noartwork;
                cellEmbeded.Caption = Verbal.NoEmbedded;
            }
            track.Dispose();
        }
Пример #43
0
        private void OnReceive(IAsyncResult ar)
        {
            //try
            {
                if (!SocketConnected(_clientSocket))
                {
                    MessageBox.Show("Разорвано соединение с сервером!");
                    return;
                }
                _clientSocket.EndReceive(ar);
                Data msgToSend = new Data();
                Data msgReceived = new Data(byteData);
                if (msgReceived.cmdCommand == Command.PositionNext)
                    _clientSocket.BeginReceive(byteData,
                                          0,
                                          byteData.Length,
                                          SocketFlags.None,
                                          new AsyncCallback(OnReceive),
                                          null);
                //Accordingly process the message received
                switch (msgReceived.cmdCommand)
                {
                    case Command.Login:
                        if (msgReceived.strName != null)
                        {
                            lstChatters.Items.Add(msgReceived.strName);
                            txtChatBox.Text += msgReceived.strMessage + "\r\n";
                        }
                        break;

                    case Command.Logout:
                        lstChatters.Items.Remove(msgReceived.strName);
                        txtChatBox.Text += msgReceived.strMessage + "\r\n";
                        break;

                    case Command.Message:
                        txtChatBox.Text += msgReceived.strMessage + "\r\n";
                        break;

                    case Command.PositionNext:
                        mut.WaitOne();

                        using (Graphics g = Graphics.FromImage(pictureBox1.Image))
                        {
                            //g.Clear(Color);
                            g.DrawLine(new Pen(msgReceived.clientColor), msgReceived.pnt1, msgReceived.pnt2);
                        }
                        //_bitmap.SetPixel(X, Y, msgReceived.clientColor);
                        pictureBox1.Refresh();

                        mut.ReleaseMutex();

                        break;

                    case Command.BitmapInfoRequest:
                        ImageConverter icReq = new ImageConverter();
                        byte[] new_b = (byte[])icReq.ConvertTo(_bitmap, typeof(byte[]));

                        msgToSend.cmdCommand = Command.BitmapInfoResult;
                        msgToSend.strName = msgReceived.strName;
                        msgToSend.strMessage = "L " + new_b.Length.ToString();

                        byteData = msgToSend.ToByte();
                        _clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);

                        System.Threading.Thread.Sleep(100);

                        msgToSend.bmp = new_b;
                        msgToSend.strMessage = "B";

                        byteData = msgToSend.ToByte();
                        _clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                        break;

                    case Command.BitmapInfoResult:
                        if (msgReceived.strMessage[0] == 'L')
                            byteData = new byte[System.Convert.ToInt32(msgReceived.strMessage.Split(' ')[1])+50];
                        else
                        {
                            ImageConverter icRes = new ImageConverter();
                            Image img = (Image)icRes.ConvertFrom(msgReceived.bmp);
                            _bitmap = new Bitmap(img);
                            pictureBox1.Image = _bitmap;
                            pictureBox1.Refresh();
                        }
                        break;

                    case Command.ClientList:
                        lstChatters.Items.AddRange(msgReceived.strMessage.Split('*'));
                        lstChatters.Items.RemoveAt(lstChatters.Items.Count - 1);
                        txtChatBox.Text += "<<<" + strName + " has joined the room>>>\r\n";

                        msgToSend = new Data();
                        msgToSend.cmdCommand = Command.BitmapInfoRequest;
                        msgToSend.strName = strName;
                        msgToSend.strMessage = null;

                        byte[] byteDataLocal = new byte[1024];
                        byteDataLocal = msgToSend.ToByte();

                        _clientSocket.BeginSend(byteDataLocal, 0, byteDataLocal.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                        break;

                    case Command.TestPackageSend:
                        _testNum++;
                        break;

                    case Command.TestPackageRecieve:
                        msgToSend = new Data();
                        msgToSend.cmdCommand = Command.TestPackageRecieve;
                        msgToSend.strName = strName;
                        msgToSend.strMessage = _testNum.ToString();

                        _testNum = 0;

                        _clientSocket.BeginSend(msgToSend.ToByte(), 0, msgToSend.ToByte().Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                        break;
                }

                //if (msgReceived.strMessage != null && msgReceived.cmdCommand != Command.ClientList && msgReceived.cmdCommand != Command.PositionNext && msgReceived.cmdCommand != Command.BitmapInfoRequest && msgReceived.cmdCommand != Command.BitmapInfoResult)

                //byteData = new byte[2048];
                if (msgReceived.cmdCommand != Command.PositionNext)
                    _clientSocket.BeginReceive(byteData,
                                          0,
                                          byteData.Length,
                                          SocketFlags.None,
                                          new AsyncCallback(OnReceive),
                                          null);

            }
            /*catch (ObjectDisposedException)
            { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclientTCP: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }*/
        }
Пример #44
0
        public Image resizeImage(Image imgToResize, Size size, System.Drawing.Imaging.ImageFormat destformat, PixelFormat pixel_format)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(size.Width, size.Height, PixelFormat.Format1bppIndexed);

            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.Bicubic;

            g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
            g.Dispose();

            Image img = (Image)b;

            byte[] bin = imageToByteArray(img, destformat);
            //byte[] bin = DBTypes.DBtypesFunc.imageToByteArray(img);
            ImageConverter ic = new ImageConverter();
            return (Image)ic.ConvertFrom(bin);
        }
Пример #45
0
 /// <summary>Called when the current node in the XmlReader should be parsed into data for this layer</summary>
 /// <param name="reader">The XmlReader that holds the current node</param>
 protected override void readDataFromXml(XmlReader reader)
 {
     // Read the image data
     if (reader.Name == "image-data")
     {
         reader.Read();
         while (reader.NodeType != XmlNodeType.EndElement || reader.Name != "image-data")
         {
             if (reader.NodeType == XmlNodeType.CDATA)
             {
                 ImageConverter icer = new ImageConverter();
                 String imageString = reader.ReadContentAsString(); // The image as base64 string
                 byte[] imageData = Convert.FromBase64String(imageString);
                 bitmap = (Bitmap)icer.ConvertFrom(imageData);
             }
         }
     }
     // Let the base class read its data
     else
         base.readDataFromXml(reader);
 }
Пример #46
0
        private OperationResult<NoType> CreateImageFile(string imageName, byte[] byteArrayImage)
        {
            ImageConverter ic = new ImageConverter();
            Image img;
            try
            {
                img = (Image)ic.ConvertFrom(byteArrayImage);
            }
            catch
            {
                return OperationResult<NoType>.BadResult("Erreur : Conversion B64 -> Image a echoué.");
            }

            string imageServerDirectory = HttpContext.Current.Server.MapPath("~/Content/VideoThumbs");
            string filesavePath = Path.Combine(imageServerDirectory, string.Format("{0}.jpg", imageName));
            try
            {
                using (Bitmap bitmap1 = new Bitmap(img))
                {
                    bitmap1.Save(filesavePath);
                }
            }
            catch
            {
                return OperationResult<NoType>.BadResult("Erreur : Sauvegarde du fichier image a échoué.");
            }
            return OperationResult<NoType>.OkResult;
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            var imageConverter = new System.Drawing.ImageConverter();

            return(imageConverter.ConvertFrom(byteArrayIn) as System.Drawing.Image);
        }