Esempio n. 1
1
    public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
    {
        CompareResult cr = CompareResult.ciCompareOk;

        //Test to see if we have the same size of image
        if (bmp1.Size != bmp2.Size)
        {
            cr = CompareResult.ciSizeMismatch;
        }
        else
        {
            //Convert each image to a byte array
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());

            //Compute a hash for each image
            SHA256Managed shaM = new SHA256Managed();
            byte[] hash1 = shaM.ComputeHash(btImage1);
            byte[] hash2 = shaM.ComputeHash(btImage2);

            //Compare the hash values
            for (int i = 0; i < hash1.Length && i < hash2.Length && cr == CompareResult.ciCompareOk; i++)
            {
                if (hash1[i] != hash2[i])
                    cr = CompareResult.ciPixelMismatch;
            }
            shaM.Clear();
        }

        return cr;
    }
Esempio n. 2
0
 public static byte[] GetByteArrayFromImage(Image image)
 {
     ImageConverter converter = new ImageConverter();
     byte[] imgArray = (byte[])converter.ConvertTo(image, typeof(byte[]));
     //TODO: check to see if this needs a dispose
     return imgArray;
 }
Esempio n. 3
0
		protected Image GetPhoto() {
			if((photo == null) && (Photo_Binary != null)) {
				ImageConverter imageConverter = new ImageConverter();
				photo = (Image)imageConverter.ConvertFrom(Photo_Binary);
			}
			return photo;
		}
Esempio n. 4
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);
        }
    }
Esempio n. 5
0
 public void GetGifPalette(Bitmap bit)
 {
     using (MemoryStream imageStreamSource
                = new MemoryStream())
     {
         System.Drawing.ImageConverter ic
             = new System.Drawing.ImageConverter();
         byte[] btImage
             = (byte[])ic.ConvertTo(bit, typeof(byte[]));
         imageStreamSource.Write(btImage, 0, btImage.Length);
         GifBitmapDecoder decoder
             = new GifBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         BitmapPalette pal
             = decoder.Palette;
         int i;
         for (i
                  = 0; i < 0x100; i++)
         {
             this.Palette[i]
                 = 0;
         }
         try
         {
             i
                 = 0;
             while (i < 0x100)                    //&& i < pal.Colors.Count)
             {
                 int Red
                     = pal.Colors[i].R / 8;
                 int Green
                     = pal.Colors[i].G / 8;
                 int Blue
                     = pal.Colors[i].B / 8;
                 int contaFinal
                     = (((0x400 * Red) + (0x20 * Green)) + Blue) + 0x8000;
                 if (contaFinal == 0x8000)
                 {
                     contaFinal
                         = 0x8001;
                 }
                 this.Palette[i]
                     = (ushort)contaFinal;
                 i++;
             }
         }
         catch (System.IndexOutOfRangeException)
         { }
         catch (System.ArgumentOutOfRangeException)
         { }
         for (i
                  = 0; i < 0x100; i++)
         {
             if (this.Palette[i] < 0x8000)
             {
                 this.Palette[i]
                     = 0x8000;
             }
         }
     }
 }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var bmp = value as Bitmap;
			if (bmp == null) return;
			var converter = new ImageConverter();
			writer.WriteValue(Convert.ToBase64String((byte[])converter.ConvertTo(bmp, typeof(byte[]))));
		}
        public static byte[] ImageToByte(Image img)
        {
            ImageConverter converter = new ImageConverter();
            MessageBox.Show("metodo ImageToByte:" + "" + (byte[])converter.ConvertTo(img, typeof(byte[])));

            return (byte[])converter.ConvertTo(img, typeof(byte[]));
        }
Esempio n. 8
0
        public static ImageInfo toImgur(Bitmap bmp)
        {
            ImageConverter convert = new ImageConverter();
            byte[] toSend = (byte[])convert.ConvertTo(bmp, typeof(byte[]));
            using (WebClient wc = new WebClient())
            {
                NameValueCollection nvc = new NameValueCollection
                {
                    { "image", Convert.ToBase64String(toSend) }
                };
                wc.Headers.Add("Authorization", Imgur.getAuth());
                ImageInfo info = new ImageInfo();
                try  
                {
                    byte[] response = wc.UploadValues("https://api.imgur.com/3/upload.xml", nvc);
                    string res = System.Text.Encoding.Default.GetString(response);

                    var xmlDoc = new System.Xml.XmlDocument();
                    xmlDoc.LoadXml(res);
                    info.link = new Uri(xmlDoc.SelectSingleNode("data/link").InnerText);
                    info.deletehash = xmlDoc.SelectSingleNode("data/deletehash").InnerText;
                    info.id = xmlDoc.SelectSingleNode("data/id").InnerText;
                    info.success = true;
                }
                catch (Exception e)
                {
                    info.success = false;
                    info.ex = e;
                }
                return info;
            }
        }
Esempio n. 9
0
        public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
        {
            CompareResult cr = CompareResult.ciCompareOk;
            // removed the size test - all images compared will be the same size! (32-bit x height x width)

            //Convert each image to a byte array
            System.Drawing.ImageConverter ic =
                   new System.Drawing.ImageConverter();
            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());

            //Compute a hash for each image
            //Pointless to use SHA256 when MD5 is good enough. Speed advantage is worth it here.
            MD5 shaM = new MD5CryptoServiceProvider();
            byte[] hash1 = shaM.ComputeHash(btImage1);
            byte[] hash2 = shaM.ComputeHash(btImage2);

            //Compare the hash values
            for (int i = 0; i < hash1.Length && i < hash2.Length && cr == CompareResult.ciCompareOk; i++)
            {
                if (hash1[i] != hash2[i])
                    cr = CompareResult.ciPixelMismatch;
            }

            return cr;
        } // end function
Esempio n. 10
0
        public byte[] GenerateTextImage(string text, string stringFont, int fontSize, FontStyle[] fontStyles, string stringColor, Size imageSize, bool isVertical)
        {
            fontSize = (fontSize == 0 ? 1024 : fontSize);

            Color color = new Color();
            try
            {
                color = ColorTranslator.FromHtml(stringColor);
            }
            catch { }

            FontStyle styles = FontStyle.Regular;
            if (fontStyles != null)
            {
                foreach (FontStyle style in fontStyles)
                {
                    styles |= style;
                }
            }

            Image image = ImageProcessor.GenerateTextImage(text, new Font(stringFont, fontSize, styles), new SolidBrush(color), isVertical);

            if (imageSize != null && imageSize.Width > 0 && imageSize.Height > 0)
            {
                image = new Bitmap(image, imageSize);
            }

            ImageConverter converter = new ImageConverter();
            return (byte[])converter.ConvertTo(image, typeof(byte[]));
        }
Esempio n. 11
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);
        }
        private Image byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            Image img = (Image)converter.ConvertFrom(byteArrayIn);

            return img;
        }
Esempio n. 13
0
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            Image img = (Image)converter.ConvertFrom(byteArrayIn);

            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;
 }
Esempio n. 15
0
 /// <summary>
 /// Load image to the texture.
 /// </summary>
 /// <param name="image"></param>
 public void LoadImage(System.Drawing.Bitmap image)
 {
     System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
     texture = SharpDX.Direct3D9.Texture.FromMemory(device.device, (byte[])converter.ConvertTo(image, typeof(byte[])),
                                                    (int)(image.Width), (int)(image.Height), 1, SharpDX.Direct3D9.Usage.None, SharpDX.Direct3D9.Format.A8R8G8B8, SharpDX.Direct3D9.Pool.Default, SharpDX.Direct3D9.Filter.Linear, SharpDX.Direct3D9.Filter.Linear, 0);
     imageSize = image.Size;
 }
Esempio n. 16
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node) :
            base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlNode picNode = node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip", drawings.NameSpaceManager);
            if (picNode != null)
            {
                RelPic = drawings.Part.GetRelationship(picNode.Attributes["r:embed"].Value);
                UriPic = PackUriHelper.ResolvePartUri(drawings.UriDrawing, RelPic.TargetUri);

                Part = drawings.Part.Package.GetPart(UriPic);
                FileInfo f = new FileInfo(UriPic.OriginalString);
                ContentType = GetContentType(f.Extension);
                _image = Image.FromStream(Part.GetStream());
                ImageConverter ic=new ImageConverter();
                var iby=(byte[])ic.ConvertTo(_image, typeof(byte[]));
                var ii = _drawings._package.LoadImage(iby, UriPic, Part);
                ImageHash = ii.Hash;

                string relID = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@r:id");
                if (!string.IsNullOrEmpty(relID))
                {
                    HypRel = drawings.Part.GetRelationship(relID);
                    if (HypRel.TargetUri.IsAbsoluteUri)
                    {
                        _hyperlink = new ExcelHyperLink(HypRel.TargetUri.AbsoluteUri);
                    }
                    else
                    {
                        _hyperlink = new ExcelHyperLink(HypRel.TargetUri.OriginalString, UriKind.Relative);
                    }
                    ((ExcelHyperLink)_hyperlink).ToolTip = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@tooltip");
                }
            }
        }
Esempio n. 17
0
        public string Upload(Image image)
        {
            ImageConverter converter = new ImageConverter();
            byte[] imageData = (byte[])converter.ConvertTo(image, typeof(byte[]));

            if (imageData == null)
                return string.Empty;

            try
            {
                string fileName = String.Format("{0}.png", DateTime.Now.ToString("dd.MM.yyyy-HH.mm.ss"));
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}/{2}", settings.Server, settings.Directory, fileName));
                {
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(settings.Username, settings.Password);
                    request.UsePassive = true;
                    request.UseBinary = true;
                    request.KeepAlive = false;
                    request.ReadWriteTimeout = 15000;
                    request.Timeout = 15000;
                }

                Stream reqStream = request.GetRequestStream();
                reqStream.Write(imageData, 0, imageData.Length);
                reqStream.Close();

                return String.Format("{0}/{1}", settings.Url, fileName);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Esempio n. 18
0
        public static Image byteArrayToImage(byte[] byteArrayIn)
        {
            ImageConverter imageConverter = new System.Drawing.ImageConverter();
            Image          image          = imageConverter.ConvertFrom(byteArrayIn) as Image;

            return(image);
        }
Esempio n. 19
0
 public static void ConvertImageToDataString(Picture pictureToSave, Stream stream)
 {
     ImageConverter IC = new ImageConverter();
     Image image = Image.FromStream(stream);
     image = PictureResizer.ScaleImage(image, 600, 400);
     pictureToSave.PictureData = Convert.ToBase64String(PictureResizer.GetByteArrayFromImage(image));
 }
Esempio n. 20
0
        /// <summary>
        /// Compare two images
        /// </summary>
        /// <param name="bmp1"></param>
        /// <param name="bmp2"></param>
        /// <returns>true if identical</returns>
        public static bool CompareImages(Image bmp1, Image bmp2)
        {
            //Test to see if we have the same size of image
            if (bmp1.Size != bmp2.Size)
            {
                return(false);
            }

            //Convert each image to a byte array
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());

            // Compute a hash for each image
            SHA256Managed shaM = new SHA256Managed();

            byte[] hash1 = shaM.ComputeHash(btImage1);
            byte[] hash2 = shaM.ComputeHash(btImage2);

            //Compare the hash values
            for (int i = 0; i < hash1.Length && i < hash2.Length; i++)
            {
                if (hash1[i] != hash2[i])
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 21
0
        /// <summary>
        /// Donne le byte[] d'une image grâce à son chemin
        /// </summary>
        public static byte[] ImageToByte(string path)
        {
            Image oldImage = Image.FromFile(path);

            // Définie les nouvelles height et with
            int newWidth;
            int newHeight;
            if (oldImage.Width > oldImage.Height)
            {
                newWidth = 120;
                newHeight = 120 * oldImage.Height / oldImage.Width;
            }
            else
            {
                newHeight = 120;
                newWidth = 120 * oldImage.Width / oldImage.Height;
            }

            // Redimensionne l'image
            Bitmap newImage = new Bitmap(newWidth, newHeight);
            Graphics resizer = Graphics.FromImage(newImage);
            resizer.InterpolationMode = InterpolationMode.HighQualityBicubic;
            resizer.DrawImage(oldImage, 0, 0, newWidth, newHeight);

            // Transforme l'image en byte[]
            ImageConverter converter = new ImageConverter();
            byte[] newImageByteArray = (byte[])converter.ConvertTo(newImage, typeof(byte[]));

            // Libération mémoire
            oldImage.Dispose();
            newImage.Dispose();
            resizer.Dispose();

            return newImageByteArray;
        }
Esempio n. 22
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var qr = new ZXing.BarcodeWriter();//new instance of a barcodewriter class
                qr.Options = options;
                qr.Format  = ZXing.BarcodeFormat.QR_CODE;
                var result = new Bitmap(qr.Write(textBox1.Text.Trim()));
                Img.Image = result;
                Bitmap bmp1 = new Bitmap(Img.Image);
                //Bitmap bmp2 = new Bitmap(ImgThumb.Image);
                System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
                byte[] btImage1 = new byte[1];
                btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
                // byte[] img = ReadImageFile(label6.Text);

                SaveFileDialog save = new SaveFileDialog();
                save.CreatePrompt    = true;
                save.OverwritePrompt = true;
                save.FileName        = textBox1.Text;
                save.Filter          = "PNG|*.png|JPEG|*.jpg|BMP|*.bmp|GIF|*.gif";
                if (save.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Img.Image.Save(save.FileName);
                    save.InitialDirectory = Environment.GetFolderPath
                                                (Environment.SpecialFolder.Desktop);
                }
                MessageBox.Show("Register Successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Enter Correct Value");
            }
        }
Esempio n. 23
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;
            }
Esempio n. 24
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]);
        }
    }
Esempio n. 25
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]);
        }
    }
        /// <summary>
        /// 对比两张图片
        /// </summary>
        /// <param name="bmp1">The first bitmap image</param>
        /// <param name="bmp2">The second bitmap image</param>
        /// <returns>CompareResult</returns>
        public static CompareResult CompareTwoImages(Bitmap bmp1, Bitmap bmp2)
        {
            CompareResult cr = CompareResult.CompareOk;

            //Test to see if we have the same size of image
            if (bmp1.Size != bmp2.Size)
            {
                cr = CompareResult.SizeMismatch;
            }
            else
            {
                //Convert each image to a byte array
                System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
                byte[] btImage1 = new byte[1];
                btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
                byte[] btImage2 = new byte[1];
                btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());

                //Compute a hash for each image
                SHA256Managed shaM  = new SHA256Managed();
                byte[]        hash1 = shaM.ComputeHash(btImage1);
                byte[]        hash2 = shaM.ComputeHash(btImage2);

                //Compare the hash values
                for (int i = 0; i < hash1.Length && i < hash2.Length &&
                     cr == CompareResult.CompareOk; i++)
                {
                    if (hash1[i] != hash2[i])
                    {
                        cr = CompareResult.PixelMismatch;
                    }
                }
            }
            return(cr);
        }
Esempio n. 27
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            IPEndPoint IPE = new IPEndPoint(IPAddress.Parse(ClientIPtextBox.Text), int.Parse(ClientPorttextBox.Text));

            if (client.Connected)
            {
                STW.WriteLine(TextToSend);
                this.ChatScreentextBox.Invoke(new MethodInvoker(delegate()
                {
                    ChatScreentextBox.AppendText("Me:" + TextToSend + "\n");
                }));
            }
            else
            {
                MessageBox.Show("Sending failed");
            }
            backgroundWorker2.CancelAsync();

            sListen.Bind(IPE);
            sListen.Listen(2);

            while (button11.Text == "button10")
            {
                Socket clientSocket;
                clientSocket = sListen.Accept();

                var    converter = new System.Drawing.ImageConverter();
                byte[] buffer    = (byte[])converter.ConvertTo(img3, typeof(byte[]));
                clientSocket.Send(buffer, buffer.Length, SocketFlags.None);
            }
        }
        //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;
        }
Esempio n. 29
0
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4)
            {
                // -------------- Loading An Image From File ---------------
                // ------------------- As Bytes Array ----------------------

                var ofd = new OpenFileDialog();

                if (ofd.ShowDialog() != DialogResult.OK)
                    return;

                Image img = Image.FromFile(ofd.FileName);

                // Converting An Image To Array Of Bytes
                ImageConverter converter = new ImageConverter();
                byte[] imgBytes = (byte[])converter.ConvertTo(img, typeof(byte[]));

                // Removing Image From RAM
                // Also, you can use "uses" keyword for Auto Dispose
                img.Dispose();
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = imgBytes;
                ((DataGridViewImageColumn)dataGridView1.Columns[e.ColumnIndex]).ImageLayout = DataGridViewImageCellLayout.Zoom;

            }
        }
Esempio n. 30
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.");
            }
        }
Esempio n. 31
0
    // Use this for initialization
    void Start()
    {
        try
        {
            StartClient();
            keyboard = new Keyboard();
        }
        catch
        {
            Console.WriteLine("pas de connection");
        }


        local_image   = new Dictionary <int, System.Drawing.Image>();
        isImageCanUse = new Dictionary <int, bool>();

        local_image[0]   = System.Drawing.Image.FromFile(Application.dataPath + "/Resources/1.jpg");
        isImageCanUse[0] = false;
        texture          = new Texture2D(local_image[0].Width, local_image[0].Height);
        imageConverter   = new System.Drawing.ImageConverter();
        imageData        = (byte[])imageConverter.ConvertTo(local_image[0], typeof(byte[]));
        texture.LoadImage(imageData);

        meshRenderer = GetComponent <MeshRenderer>();
        meshRenderer.material.mainTexture = texture;
    }
Esempio n. 32
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();
     }
 }
Esempio n. 33
0
        //convert bitmap to byte (serialize)
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Bitmap bitmap = (Bitmap)value;

            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            writer.WriteValue((byte[])converter.ConvertTo(bitmap, typeof(byte[])));
        }
        public ActionResult Index(HttpPostedFileBase image)
        {
            if (image == null) return Index("Where's the beef?");
            var imageStreamConverter = new ImageStreamConverter();
            var bitmap = imageStreamConverter.GetBitmapFromPostedFile(image);

            if (bitmap == null) return Index("That's not an image, homie...");

            var serviceBusConnectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
            var blobConnectionString = CloudConfigurationManager.GetSetting("BlobStorage.ConnectionString");

            var storageAccount = CloudStorageAccount.Parse(blobConnectionString);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference("images");
            container.CreateIfNotExists();

            var blockReference = container.GetBlockBlobReference(image.FileName);
            var converter = new ImageConverter();
            var bitmapBytes = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));

            blockReference.UploadFromByteArray(bitmapBytes, 0, bitmapBytes.Length);

            var namespaceManager = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);

            if (!namespaceManager.QueueExists("ImageProcessing"))
            {
                namespaceManager.CreateQueue("ImageProcessing");
            }

            var client = QueueClient.CreateFromConnectionString(serviceBusConnectionString, "ImageProcessing");
            var message = new BrokeredMessage(new ImageMessage { BlobBlockName = blockReference.Name });

            client.Send(message);
            return Index();
        }
 public static Byte[] ImageToByte(System.Drawing.Image image)
 {
     System.Drawing.ImageConverter imgConverter = new System.Drawing.ImageConverter();
     Byte[] bytes;
     bytes = (Byte[])(imgConverter.ConvertTo(image, typeof(Byte[])));
     return(bytes);
 }
 public Bitmap convert_ByteArrayToBitmap(byte[,] byteArray)
 {
     ImageConverter ic = new ImageConverter();
     Image img = (Image)ic.ConvertFrom(byteArray);
     Bitmap bitmap1 = new Bitmap(img);
     return bitmap1;
 }
 private byte[] ComputeIconHash(Icon icon)
 {
     ImageConverter converter = new ImageConverter();
     byte[] rawIcon = converter.ConvertTo(icon.ToBitmap(), typeof(byte[])) as byte[];
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     return md5.ComputeHash(rawIcon);
 }
Esempio n. 38
0
        public void ImageTest()
        {
            Image image = Image.FromFile(@"c:\temp\google.png");

            ImageConverter converter = new ImageConverter();

            var bytes = (byte[])converter.ConvertTo(image, typeof(byte[]));
        }
Esempio n. 39
0
 public static byte[] ImageToByteArray(Image imageIn)
 {
     var converter = new ImageConverter();
     using (var tmp = new Bitmap(imageIn))
     {
         return (byte[]) converter.ConvertTo(tmp.Clone(), typeof (byte[]));
     }
 }
        private byte[] GetImageAsByteArray(Image image)
        {                             
            if (image == null)
                throw new NullReferenceException(nameof(image));

            var converter = new ImageConverter();
            return converter.ConvertTo(image, typeof(byte[])) as byte[];
        }
Esempio n. 41
0
        public void TestUploadMultiplePhotoMemories()
        {
            var converter = new ImageConverter();
            var bytes1 = (Byte[])converter.ConvertTo(TestBacking.GetCreatePhoto(), typeof(Byte[]));
            var bytes2 = (Byte[])converter.ConvertTo(TestBacking.GetCreatePhoto(), typeof(Byte[]));
            var dataSource1 = new BasicDataSource(Guid.NewGuid().ToString("n") + ".jpg", "image/jpeg", bytes1);
            var dataSource2 = new BasicDataSource(Guid.NewGuid().ToString("n") + ".jpg", "image/jpeg", bytes2);
            var description = new SourceDescription().SetTitle(new TextValue().SetValue("PersonImage")).SetCitation("Citation for PersonImage");
            var artifacts = new List<IDataSource>();

            artifacts.Add(dataSource1);
            artifacts.Add(dataSource2);

            IRestRequest request = new RedirectableRestRequest()
                .AddHeader("Authorization", "Bearer " + tree.CurrentAccessToken)
                .Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE)
                .ContentType(MediaTypes.MULTIPART_FORM_DATA_TYPE)
                .Build("https://sandbox.familysearch.org/platform/memories/memories", Method.POST);

            foreach (var artifact in artifacts)
            {
                String mediaType = artifact.ContentType;

                foreach (TextValue value in description.Titles)
                {
                    request.AddFile("title", Encoding.UTF8.GetBytes(value.Value), null, MediaTypes.TEXT_PLAIN_TYPE);
                }

                foreach (SourceCitation citation in description.Citations)
                {
                    request.AddFile("citation", Encoding.UTF8.GetBytes(citation.Value), null, MediaTypes.TEXT_PLAIN_TYPE);
                }

                if (artifact.Name != null)
                {
                    request.Files.Add(new FileParameter()
                    {
                        Name = "artifact",
                        FileName = artifact.Name,
                        ContentType = artifact.ContentType,
                        Writer = new Action<Stream>(s =>
                        {
                            artifact.InputStream.Seek(0, SeekOrigin.Begin);
                            using (var ms = new MemoryStream(artifact.InputStream.ReadAsBytes()))
                            using (var reader = new StreamReader(ms))
                            {
                                reader.BaseStream.CopyTo(s);
                            }
                        })
                    });
                }
            }

            var state = tree.Client.Handle(request);

            Assert.IsNotNull(state);
            Assert.AreEqual(HttpStatusCode.Created, state.StatusCode);
        }
Esempio n. 42
0
        public MemoryStream InsertImage()
        {
            Bitmap b = new Bitmap(Properties.Resources.KICALogo__low_res_);
            ImageConverter ic = new ImageConverter();
            Byte[] ba = (Byte[])ic.ConvertTo(b, typeof(Byte[]));
            MemoryStream logo = new MemoryStream(ba);

            return logo;
        }
        // Генерируем и возвращаем изображение // Генерируется задача в зависимости от присланного номера
        public static string CheckLatex(string code)
        {
            Bitmap bmp = MathMLFormulaControl.generateBitmapFromLatex(code);

            ImageConverter converter = new ImageConverter();
            var bytes = (byte[])converter.ConvertTo(bmp, typeof(byte[]));

            return Convert.ToBase64String(bytes);
        }
Esempio n. 44
0
 public Texture(IDevice device, System.Drawing.Bitmap image)
 {
     this.device = (Device)device;
     System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
     texture = SharpDX.Direct3D9.Texture.FromMemory(((Device)device).device, (byte[])converter.ConvertTo(image, typeof(byte[])),
                                                    (int)(image.Width), (int)(image.Height), 1, SharpDX.Direct3D9.Usage.None, SharpDX.Direct3D9.Format.A8R8G8B8, SharpDX.Direct3D9.Pool.Default, SharpDX.Direct3D9.Filter.Linear, SharpDX.Direct3D9.Filter.Linear, 0);
     imageSize = image.Size;
     sprite    = new SharpDX.Direct3D9.Sprite(this.device.device);
 }
 public static byte[] ConvertImageToByteArray(Image image)
 {
     /* MemoryStream stream = new MemoryStream();
      * image.Save(stream, image.RawFormat);
      * stream.Position = 0;
      * return stream.ToArray();*/
     System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
     return((byte[])converter.ConvertTo(image, typeof(byte[])));
 }
Esempio n. 46
0
        public void ResizeTest()
        {
            var bitmap = new Bitmap(100, 100);
            ImageConverter converter = new ImageConverter();
            var arr = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            ImageProcessor target = new ImageProcessor { Image = arr };
            int maxWidth = 100;
            int maxHeight = 50;
            target.Resize(maxWidth, maxHeight);
            Assert.IsTrue(target.Width <= maxWidth);
            Assert.IsTrue(target.Height <= maxHeight);
            Assert.AreEqual(bitmap.Width / bitmap.Height, target.Width / target.Height);

            bitmap = new Bitmap(150, 250);
            arr = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            target.Image = arr;
            target.Resize(maxWidth, maxHeight);
            Assert.IsTrue(target.Width <= maxWidth);
            Assert.IsTrue(target.Height <= maxHeight);
            Assert.AreEqual(bitmap.Width / bitmap.Height, target.Width / target.Height);

            bitmap = new Bitmap(250, 100);
            arr = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            target.Image = arr;
            target.Resize(maxWidth, maxHeight);
            Assert.IsTrue(target.Width <= maxWidth);
            Assert.IsTrue(target.Height <= maxHeight);
            Assert.AreEqual(bitmap.Width / bitmap.Height, target.Width / target.Height);

            maxWidth = 50;
            maxHeight = 100;

            bitmap = new Bitmap(100, 100);
            arr = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            target.Image = arr;
            target.Resize(maxWidth, maxHeight);
            Assert.IsTrue(target.Width <= maxWidth);
            Assert.IsTrue(target.Height <= maxHeight);
            Assert.AreEqual(bitmap.Width / bitmap.Height, target.Width / target.Height);

            bitmap = new Bitmap(150, 250);
            arr = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            target.Image = arr;
            target.Resize(maxWidth, maxHeight);
            Assert.IsTrue(target.Width <= maxWidth);
            Assert.IsTrue(target.Height <= maxHeight);
            Assert.AreEqual(bitmap.Width / bitmap.Height, target.Width / target.Height);

            bitmap = new Bitmap(250, 100);
            arr = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));
            target.Image = arr;
            target.Resize(maxWidth, maxHeight);
            Assert.IsTrue(target.Width <= maxWidth);
            Assert.IsTrue(target.Height <= maxHeight);
            Assert.AreEqual(bitmap.Width / bitmap.Height, target.Width / target.Height);
        }
Esempio n. 47
0
        public static string GetHashImage(Bitmap bmp1)
        {
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
            SHA256Managed shaM = new SHA256Managed();

            // Retorna string de base 64
            return(System.Convert.ToBase64String((shaM.ComputeHash(btImage1))));
        }
Esempio n. 48
0
 // http://www.codeproject.com/dotnet/comparingimages.asp
 private string GetHashFromImage(Image image)
 {
     System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
     byte[] imageBytes = new byte[1];
     imageBytes = (byte[])ic.ConvertTo(image, imageBytes.GetType());
     System.Security.Cryptography.MD5CryptoServiceProvider md5 =
         new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] hashBytes = md5.ComputeHash(imageBytes);
     return(BitConverter.ToString(hashBytes));
 }
Esempio n. 49
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);
 }
Esempio n. 50
0
        private static byte[] GetGdiImageBytes(GDI.Image gdiImage)
        {
            if (gdiImage == null)
            {
                return(Array.Empty <byte>());
            }

            var converter = new GDI.ImageConverter();

            return((byte[])converter.ConvertTo(gdiImage, typeof(byte[])));
        }
Esempio n. 51
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));
        }
Esempio n. 52
0
        public Piece(int number, Bitmap img)
        {
            this.number = number;
            this.img    = img;
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[] tempimg = new byte[1];
            tempimg = (byte[])ic.ConvertTo(img, tempimg.GetType());
            MD5 shaM = new MD5CryptoServiceProvider();

            this.checksum = Convert.ToBase64String(shaM.ComputeHash(tempimg)).Replace('/', 'x');
        }
Esempio n. 53
0
        public object ConvertBack(object image, Type targetType, object parameter, CultureInfo culture)
        {
            var bitmapImage = image as Bitmap;

            if (bitmapImage != null)
            {
                System.Drawing.ImageConverter _imageConverter = new System.Drawing.ImageConverter();
                byte[] byteArrayImage = (byte[])_imageConverter.ConvertTo(bitmapImage, typeof(byte[]));
                return(byteArrayImage);
            }
            return(null);
        }
        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;
        }
Esempio n. 55
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();
            }
        }
Esempio n. 56
0
        private static void SendImage(HttpListenerResponse httpListenerResponse, string extantion)
        {
            Bitmap   primaryscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics      = Graphics.FromImage(primaryscreen as Image);

            graphics.CopyFromScreen(0, 0, 0, 0, primaryscreen.Size);
            httpListenerResponse.ContentType = "image/" + extantion;
            System.Drawing.Image          img       = (System.Drawing.Image)primaryscreen;
            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            byte[] buffer = (byte[])converter.ConvertTo(img, typeof(byte[]));
            httpListenerResponse.ContentLength64 = buffer.Length;
            System.IO.Stream output = httpListenerResponse.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
Esempio n. 57
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);
    }
Esempio n. 58
0
    // Use this for initialization
    void Start()
    {
        local_image   = new Dictionary <int, System.Drawing.Image>();
        isImageCanUse = new Dictionary <int, bool>();

        local_image[0]   = System.Drawing.Image.FromFile(Application.dataPath + "\\Resources\\1.jpg");
        isImageCanUse[0] = false;
        Texture2D texture = new Texture2D(local_image[0].Width, local_image[0].Height);

        System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
        byte[] imageData = (byte[])imageConverter.ConvertTo(local_image[0], typeof(byte[]));
        texture.LoadImage(imageData);

        meshRenderer = GetComponent <MeshRenderer>();
        meshRenderer.material.mainTexture = texture;
    }
Esempio n. 59
0
 // Update is called once per frame
 void Update()
 {
     Debug.Log("Update : " + isImageCanUse);
     if (isImageCanUse[0])
     {
         Debug.Log("writing image");
         Texture2D texture = new Texture2D(local_image[0].Width, local_image[0].Height);
         System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
         byte[] imageData = (byte[])imageConverter.ConvertTo(local_image[0], typeof(byte[]));
         texture.LoadImage(imageData);
         //spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
         //image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
         //print(1);
         meshRenderer.material.mainTexture = texture;
     }
 }