Пример #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;
    }
        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[]));
        }
        /// <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);
        }
Пример #4
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);
        }
Пример #5
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
Пример #6
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);
        }
Пример #7
0
        public Image(Bitmap bmp)
        {
            //load code
            Pixel np=new Pixel();
            m_width = (uint)bmp.Width;
            m_height = (uint)bmp.Height;
            m_needFlush = false;

            if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                m_components = 3;
            }
            else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed ||
                     bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed ||
                     bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                m_components = 4;
            }
            else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                m_components = 1;
            }

            ImageConverter imageConverter = new ImageConverter();
             m_buffer = (byte[])imageConverter.ConvertTo(bmp, typeof(byte[]));
        }
Пример #8
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[]));
        }
Пример #9
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");
            }
        }
Пример #10
0
		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[]))));
		}
Пример #11
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[])));
        }
Пример #12
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;
        }
 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);
 }
Пример #14
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;

            }
        }
Пример #15
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 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();
        }
Пример #17
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);
            }
        }
Пример #18
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;
 }
Пример #19
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");
                }
            }
        }
 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);
 }
Пример #21
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;
 }
Пример #22
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;
            }
        }
Пример #23
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;
    }
Пример #24
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;
            }
        }
Пример #25
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[]));
     }
 }
Пример #26
0
        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[];
        }
Пример #27
0
        public void ImageTest()
        {
            Image image = Image.FromFile(@"c:\temp\google.png");

            ImageConverter converter = new ImageConverter();

            var bytes = (byte[])converter.ConvertTo(image, typeof(byte[]));
        }
Пример #28
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);
        }
 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[])));
 }
Пример #31
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));
 }
Пример #32
0
        public static void SaveAsNot32BitImage(this Image img, string fname)
        {
            var bmp = new Bitmap(img.Width, img.Height, img.PixelFormat);
            using (var gr = Graphics.FromImage(bmp))
                gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));

            ImageConverter imgCon = new ImageConverter();
            var bytes = (byte[])imgCon.ConvertTo(bmp, typeof(byte[]));
            File.WriteAllBytes(fname, bytes);
        }
Пример #33
0
        private bool Compare(int index)
        {
            if (m_Compare.ContainsKey(index))
            {
                return(m_Compare[index]);
            }
            Bitmap bitorg = Textures.GetTexture(index);
            Bitmap bitsec = SecondTexture.GetTexture(index);

            if ((bitorg == null) && (bitsec == null))
            {
                m_Compare[index] = true;
                return(true);
            }
            if (((bitorg == null) || (bitsec == null)) ||
                (bitorg.Size != bitsec.Size))
            {
                m_Compare[index] = false;
                return(false);
            }

            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bitorg, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bitsec, btImage2.GetType());

            string hash1string = BitConverter.ToString(shaM.ComputeHash(btImage1));
            string hash2string = BitConverter.ToString(shaM.ComputeHash(btImage2));

            bool res;

            if (hash1string != hash2string)
            {
                res = false;
            }
            else
            {
                res = true;
            }

            m_Compare[index] = res;
            return(res);
        }
Пример #34
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))));
        }
Пример #35
0
		protected void SetPhoto(Image value) {
			photo = value;
			if(photo != null) {
				ImageConverter imageConverter = new ImageConverter();
				Photo_Binary = (Byte[])imageConverter.ConvertTo(photo, typeof(Byte[]));
			}
			else {
				Photo_Binary = null;
			}
		}
Пример #36
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');
 }
Пример #37
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');
        }
Пример #38
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[])));
        }
Пример #39
0
 private void bbt_ok_Click(object sender, EventArgs e)
 {
     byte[] dataPicture = new byte[10000];
     MemoryStream ms = new MemoryStream();
     ImageConverter imageConvert = new ImageConverter();
     dataPicture = (byte[])imageConvert.ConvertTo(ptb_avatar.Image, typeof(byte[]));
     _Command.Command cmd = new _Command.Command(Enum.CommandType_.ChangeInformation, txt_username.Text, txt_email.Text, dataPicture, txt_status.Text);
     client.SendCommand(cmd);
     MyGetValue(ptb_avatar.Image, txt_status.Text);
     this.Close();
 }
Пример #40
0
        /*将图片转字符串*/
        private byte[] BmpToJpegBuff(Image img) {
            ImageConverter converter = new ImageConverter();
            byte[] bmpSrc = (byte[])converter.ConvertTo(img, typeof(byte[]));
            MemoryStream ms = new MemoryStream(bmpSrc);
            MemoryStream msjpg = new MemoryStream();
            Bitmap myBitmap = new Bitmap(ms);
            myBitmap.Save(msjpg, ImageFormat.Jpeg);
            byte[] bjpeg = msjpg.GetBuffer();

            return bjpeg;
        }
Пример #41
0
        private bool Compare(int index)
        {
            if (m_Compare.ContainsKey(index))
            {
                return(m_Compare[index]);
            }
            Bitmap bitorg = Art.GetStatic(index);
            Bitmap bitsec = SecondArt.GetStatic(index);

            if ((bitorg == null) && (bitsec == null))
            {
                m_Compare[index] = true;
                return(true);
            }
            if (((bitorg == null) || (bitsec == null)) ||
                (bitorg.Size != bitsec.Size))
            {
                m_Compare[index] = false;
                return(false);
            }

            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bitorg, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bitsec, btImage2.GetType());

            byte[] checksum1 = shaM.ComputeHash(btImage1);
            byte[] checksum2 = shaM.ComputeHash(btImage2);
            bool   res       = true;

            for (int j = 0; j < checksum1.Length; ++j)
            {
                if (checksum1[j] != checksum2[j])
                {
                    res = false;
                    break;
                }
            }
            m_Compare[index] = res;
            return(res);
        }
Пример #42
0
        /// <summary>
        /// Compute a MD5 checksum from a bitmap
        /// </summary>
        /// <param name="bitmap">Bitmap to compute</param>
        /// <returns>Hashed checksum</returns>
        public static byte[] ComputeChecksum(Bitmap bitmap)
        {
            //Convert each image to a byte array
            var ic = new ImageConverter();
            var ics = new byte[2];
            var bytes = (byte[])ic.ConvertTo(bitmap, ics.GetType());

            //LockBitmap lockBitmap = new LockBitmap(bitmap);
            //lockBitmap.LockBits();
            //lockBitmap.UnlockBits();
            return ComputeChecksum(bytes);
        }
Пример #43
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);
        }
Пример #44
0
        public string Upload(Image image)
        {
            ImageConverter converter = new ImageConverter();
            byte[] imageData = (byte[])converter.ConvertTo(image, typeof(byte[]));

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

            using (WebClient w = new WebClient { Proxy = null })
            {
                NameValueCollection values = new NameValueCollection
                {
                    { "key", "Jk8hh9L" },
                    { "upload", Convert.ToBase64String(imageData) },
                    { "format", "xml" }
                };

                XmlDocument xDoc = new XmlDocument();

                try
                {
                    byte[] response = w.UploadValues("http://i.zhyk.ru/api", values);
                    xDoc.Load(new MemoryStream(response));
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }

                XmlNode statusNode = xDoc.SelectSingleNode("response/status_code");

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

                if (statusNode.InnerText.Equals("200"))
                {
                    XmlNode imageNode = xDoc.SelectSingleNode("response/data/img_url");

                    if (imageNode != null)
                        return imageNode.InnerText;
                }
                else if (statusNode.InnerText.Equals("403"))
                {
                    XmlNode statusTextNode = xDoc.SelectSingleNode("response/status_txt");

                    if (statusTextNode != null)
                        return "HostingError: " + statusTextNode.InnerText;
                }

                return string.Empty;
            }
        }
Пример #45
0
 public string GetStringFromImage(Image image)
 {
     if (image != null)
     {
         ImageConverter ic = new ImageConverter();
         byte[] buffer = (byte[])ic.ConvertTo(image, typeof(byte[]));
         return Convert.ToBase64String(
             buffer,
             Base64FormattingOptions.InsertLineBreaks);
     }
     else
         return null;
 }
Пример #46
0
 private static byte[] GetTextTile(string text)
 {
     using (var image = new Bitmap(TileRequest.TileSize, TileRequest.TileSize, PixelFormat.Format32bppArgb))
       {
     var g = Graphics.FromImage(image);
     g.FillRectangle(Brushes.White, 0f, 0f, image.Width, image.Height);
     g.DrawRectangle(new Pen(Color.Blue), 0f, 0f, image.Width, image.Height);
     g.DrawString(text, new Font("Consolas", 14), Brushes.Blue, 0f, 0f);
     image.MakeTransparent(Color.White);
     var converter = new ImageConverter();
     var data = (byte[])converter.ConvertTo(image, typeof(byte[]));
     return data;
       }
 }
Пример #47
0
        private byte[] LoadFavicon()
        {
            string faviconPath = Path.Combine(_rootPathProvider.GetRootPath(), faviconFileName);

            if (File.Exists(faviconPath) == false)
            {
                return null;
            }

            var converter = new ImageConverter();

            var image = Image.FromFile(faviconPath);

            return (byte[])converter.ConvertTo(image, typeof(byte[]));
        }
Пример #48
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();
        }
Пример #49
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;
    }
Пример #50
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;
     }
 }
Пример #51
0
 // Update is called once per frame
 void Update()
 {
     keyboard.getKey(client, stream, myId, idReceive);
     Debug.Log("Update : " + isImageCanUse);
     if (isImageCanUse[0])
     {
         Debug.Log("writing image");
         texture.Resize(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);
         //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;
     }
 }
Пример #52
0
        private static ImageSource ConvertFromWinFormsImage(System.Drawing.Image image)
        {
            ImageSource imageSource = null;

            try
            {
                System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();

                byte[] imageBytes = ( byte[] )imageConverter.ConvertTo(image, typeof(byte[]));

                if (imageBytes != null)
                {
                    imageSource = ImageConverter.ConvertFromByteArray(imageBytes);
                }
            }
            catch {}

            return(imageSource);
        }
Пример #53
0
 // Update is called once per frame
 void Update()
 {
     if (Input.GetKeyDown(KeyCode.I) && Input.GetKey(KeyCode.LeftControl))
     {
         ConnectImage();
     }
     if (Input.GetKeyDown(KeyCode.U) && Input.GetKey(KeyCode.LeftControl))
     {
         DisconnectImage();
     }
     if (isImageCanUse)
     {
         Texture2D texture = new Texture2D(local_image.Width, local_image.Height);
         System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
         byte[] imageData = (byte[])imageConverter.ConvertTo(local_image, 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;
     }
 }
Пример #54
0
        /// <summary>
        /// タグ書込み
        /// </summary>
        /// <param name="row"></param>
        private void SaveTag(Row row)
        {
            string   path        = StringUtil.NullToBlank(row[(int)ColIndex.FullPath]);
            string   extension   = StringUtil.NullToBlank(row[(int)ColIndex.Extension]);
            string   title       = StringUtil.NullToBlank(row[(int)ColIndex.Title]);
            uint     year        = 0;
            DateTime releaseDate = DateTime.Parse("1900/1/1");
            string   date        = StringUtil.NullToBlank(row[(int)ColIndex.ReleaseDate]);

            if (DateTime.TryParse(date, out releaseDate))
            {
                year = (uint)releaseDate.Year;
            }
            if (extension.ToLower() == ".mp4")
            {
                //MP4のみ記入
                var tagFile = TagLib.File.Create(path);
                tagFile.Tag.Title      = title;
                tagFile.Tag.Year       = year;
                tagFile.Tag.Performers = new string[] { StringUtil.NullToBlank(row[(int)ColIndex.Artist]) };
                tagFile.Tag.Genres     = new string[] { StringUtil.NullToBlank(row[(int)ColIndex.Genres]) };
                tagFile.Tag.Comment    = StringUtil.NullToBlank(row[(int)ColIndex.Comment]);
                //画像
                Image img        = this.TargetGrid.GetCellImage(row.Index, (int)ColIndex.Image);
                var   ic         = new System.Drawing.ImageConverter();
                var   ba         = (byte[])ic.ConvertTo(img, typeof(byte[]));
                var   byteVector = new TagLib.ByteVector(ba);
                var   pic        = new TagLib.Picture(byteVector);
                pic.Type             = TagLib.PictureType.FrontCover;
                pic.Description      = "Cover";
                pic.MimeType         = System.Net.Mime.MediaTypeNames.Image.Jpeg;
                tagFile.Tag.Pictures = new TagLib.IPicture[] { pic };
                tagFile.Save();
            }
            //リネーム
            var f = new FileInfo(path);

            f.MoveTo(f.DirectoryName + @"\" + StringUtil.ReplaceWindowsFileNGWord2Wide(title) + extension.ToLower());
        }
Пример #55
0
        public ActionResult GetImage(int id)
        {
            var database = new InstagramDbContext();
            var photo    = database.Photos.Find(id);

            using (var ms = new MemoryStream(photo.Picture))
            {
                var image = System.Drawing.Image.FromStream(ms);

                var ratioX = (double)300 / image.Width;
                var ratioY = (double)300 / image.Height;
                var ratio  = Math.Min(ratioX, ratioY);

                var width  = (int)(image.Width * ratio);
                var height = (int)(image.Height * ratio);

                var newImage = new System.Drawing.Bitmap(width, height);
                System.Drawing.Graphics.FromImage(newImage).DrawImage(image, 0, 0, width, height);
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newImage);

                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();

                photo.Picture = (byte[])converter.ConvertTo(bmp, typeof(byte[]));

                var stream = new MemoryStream(photo.Picture);

                var bitmap = new Bitmap(stream);

                var newstream = new MemoryStream();
                bitmap.Save(newstream, ImageFormat.Jpeg);
                newstream.Position = 0;

                return(new FileStreamResult(newstream, "image/jpg"));


                //  return "data:image/*;base64," + Convert.ToBase64String(photo.Picture);
            }
        }
Пример #56
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (hWnd == IntPtr.Zero)
            {
                return;
            }
            /* uj screenshot */
            RECT rc;

            GetWindowRect(hWnd, out rc);
            Bitmap   bmp       = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            Graphics g         = Graphics.FromImage(bmp);
            IntPtr   hdcBitmap = g.GetHdc();

            PrintWindow(hWnd, hdcBitmap, 0);
            g.ReleaseHdc(hdcBitmap);
            g.Dispose();
            /* hash szamitasa */
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[]        bytes = (byte[])ic.ConvertTo(bmp, typeof(byte[]));
            SHA256Managed sha   = new SHA256Managed();

            byte[] hash = sha.ComputeHash(bytes);
            /* osszehasonlitas */
            if (hashPrev != null)
            {
                for (int i = 0; i < hash.Length; i++)
                {
                    if (hash[i] != hashPrev[i])
                    {
                        System.Media.SystemSounds.Asterisk.Play();
                        break;
                    }
                }
            }
            /* frissites a kovetkezo utemre */
            hashPrev = hash;
        }
Пример #57
0
    // Use this for initialization
    void Start()
    {
        local_image   = System.Drawing.Image.FromFile(Application.dataPath + "\\Resources\\1.jpg");
        isImageCanUse = false;
        port          = 50002;
        Listening     = new Thread(StartListening);
        GetImage      = new Thread(ReceiveImage);
        server        = new TcpListener(IPAddress.Any, port);
        Texture2D texture = new Texture2D(local_image.Width, local_image.Height);

        System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
        byte[] imageData = (byte[])imageConverter.ConvertTo(local_image, typeof(byte[]));
        texture.LoadImage(imageData);
        //spriteRenderer = GetComponent<SpriteRenderer>();
        //spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.0f, 0.0f));
        //this.spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.0f, 0.0f));
        meshRenderer = GetComponent <MeshRenderer>();
        meshRenderer.material.mainTexture = texture;


        BConnectImage.onClick.AddListener(ConnectImage);
        BDisconnectImage.onClick.AddListener(DisconnectImage);
        //image.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.0f, 0.0f));
    }
Пример #58
0
        public void CombineGifs(string outputPath, List <string> gifPaths, int gifsPerLine)
        {
            if (outputPath == null)
            {
                throw new ArgumentNullException(nameof(outputPath));
            }
            if (gifPaths == null)
            {
                throw new ArgumentNullException(nameof(gifPaths));
            }
            if (gifsPerLine <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(gifsPerLine));
            }

            List <MagickImageCollection> gifs = new List <MagickImageCollection>(gifPaths.Count);
            List <int> indices = new List <int>(gifPaths.Count);
            List <int> remainingAnimationTimes = new List <int>(gifPaths.Count);

            try
            {
                for (int i = 0; i < gifPaths.Count; i++)
                {
                    gifs.Add(new MagickImageCollection(gifPaths[i]));
                    indices.Add(0);
                    remainingAnimationTimes.Add(gifs[i][0].AnimationDelay);
                }

                int individualWidth  = gifs[0][0].Width;
                int individualHeight = gifs[0][0].Height;
                int width            = Math.Min(gifs.Count, gifsPerLine) * individualWidth;
                int height           = (int)Math.Ceiling(gifs.Count / (double)gifsPerLine) * individualHeight;
                using (MagickImageCollection newGif = new MagickImageCollection())
                {
                    bool doneWithAllGifs = false;
                    while (!doneWithAllGifs)
                    {
                        List <float> percentFinishedPerGif = new List <float>(gifs.Count);
                        for (int i = 0; i < gifs.Count; i++)
                        {
                            percentFinishedPerGif.Add(indices[i] / (float)gifs[i].Count);
                        }
                        OnProgress?.Invoke(percentFinishedPerGif.Average());

                        for (int i = 0; i < indices.Count; i++)
                        {
                            if (remainingAnimationTimes[i] <= 0 && indices[i] < gifs[i].Count - 1)
                            {
                                indices[i]++;
                                remainingAnimationTimes[i] = gifs[i][indices[i]].AnimationDelay;
                            }
                        }

                        doneWithAllGifs = true;
                        for (int i = 0; i < indices.Count; i++)
                        {
                            if (indices[i] < gifs[i].Count - 1)
                            {
                                doneWithAllGifs = false;
                                break;
                            }
                        }

                        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height))
                        {
                            using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
                            {
                                for (int i = 0; i < gifs.Count; i++)
                                {
                                    graphics.DrawImage(gifs[i][indices[i]].ToBitmap(), (int)Math.Floor((double)i % gifsPerLine) * individualWidth, (int)Math.Floor((double)i / gifsPerLine) * individualHeight);
                                }
                            }

                            newGif.Add(new MagickImage(bitmap));

                            int animationDelay;
                            if (!doneWithAllGifs)
                            {
                                animationDelay = int.MaxValue;
                                for (int i = 0; i < remainingAnimationTimes.Count; i++)
                                {
                                    if (indices[i] < gifs[i].Count - 1 && remainingAnimationTimes[i] > 0 && remainingAnimationTimes[i] < animationDelay)
                                    {
                                        animationDelay = remainingAnimationTimes[i];
                                    }
                                }
                            }
                            else
                            {
                                animationDelay = remainingAnimationTimes.Max();
                            }

                            newGif[newGif.Count - 1].AnimationDelay = animationDelay;

                            for (int i = 0; i < remainingAnimationTimes.Count; i++)
                            {
                                if (remainingAnimationTimes[i] > 0)
                                {
                                    remainingAnimationTimes[i] -= animationDelay;
                                }
                            }
                        }
                    }

                    long size = 0;
                    foreach (var v in newGif)
                    {
                        System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                        size += ((byte[])converter.ConvertTo(v.ToBitmap(), typeof(byte[]))).Length;
                    }
                    Console.WriteLine($"Combined GIF size: {size / 1024}KB");

                    newGif.Write(outputPath);
                }

                foreach (MagickImageCollection mic in gifs)
                {
                    mic.Dispose();
                }
            }
            catch (Exception)
            {
                foreach (MagickImageCollection mic in gifs)
                {
                    mic.Dispose();
                }

                throw;
            }
        }
Пример #59
0
        static void Main(string[] args)
        {
            Bitmap bitmap = new Bitmap(@"C:\temp\image.png");

            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            byte[] a = (byte[])converter.ConvertTo(bitmap, typeof(byte[]));

            string bbb = JsonConvert.SerializeObject(a);

            byte[] aaa = JsonConvert.DeserializeObject <byte[]>(bbb);

            Bitmap aa = new Bitmap(new MemoryStream(aaa));

            /*
             * CameraManager camera = new CameraManager();
             * var list = camera.GetDeviceList();
             *
             * camera.CameraStart(0);
             * Bitmap bitmap = camera.CaptureImage(@"C:\temp\aaa.png");
             * camera.CameraEnd();
             */
            //Screen sc = new Screen();
            //Bitmap bitmap = sc.screenCapture(300, 500, 20, 20, @"C:\Tools\e89239da.jpg");

            /*
             * string text = "";
             * Bitmap bitmap1 = new Bitmap(@"C:\Tools\e89239da.jpg");
             * Bitmap bitmap2 = new Bitmap(@"C:\Tools\e89239da_1637348035721804313.jpg");
             * Bitmap bitmap3 = new Bitmap(@"C:\Tools\e89239da_2637348035724694277.jpg");
             */
            /*
             * AzureComputerVisionApiOCR ocr = new AzureComputerVisionApiOCR();
             * ocr.initialize(@"C:\Users\tsutsumi\Downloads\azure.txt", "");
             * text = ocr.GetTextFromImage(bitmap1);
             * text = ocr.GetTextFromImage(bitmap2);
             * text = ocr.GetTextFromImage(bitmap3);
             */
            /*
             * GoogleVisionApiOCR ocr = new GoogleVisionApiOCR();
             * ocr.initialize(@"C:\Users\tsutsumi\Downloads\try-apis-8b2095f28b0e.json", "");
             * text = ocr.GetTextFromImage(bitmap1);
             * text = ocr.GetTextFromImage(bitmap2);
             * text = ocr.GetTextFromImage(bitmap3);
             */
            /*
             * TesseractOCR ocr = new TesseractOCR();
             * ocr.initialize(@"C:\Program Files\Tesseract-OCR\tessdata", "jpn");
             * text = ocr.GetTextFromImage(bitmap1);
             * text = ocr.GetTextFromImage(bitmap2);
             * text = ocr.GetTextFromImage(bitmap3);
             */
            /*
             * WindowsOCR ocr = new WindowsOCR();
             * ocr.initialize("", "ja-JP");
             * text = ocr.GetTextFromImage(bitmap1);
             * text = ocr.GetTextFromImage(bitmap2);
             * text = ocr.GetTextFromImage(bitmap3);
             */
            /*
             * List<OneHandSword> items = new List<OneHandSword>();
             * OneHandSword item = new OneHandSword();
             * item.Name = "1";
             * item.Description = "2";
             * item.Refine = 1;
             * item.Classification = 3;
             * item.BasicAbility = new List<string>();
             * item.BasicAbility.Add("4");
             * item.BasicAbility.Add("5");
             * item.BasicAbility.Add("6");
             * items.Add(item);
             * items.Add(item);
             *
             * string jsonString = JsonConvert.SerializeObject(items);
             * List<OneHandSword> newItems = JsonConvert.DeserializeObject<List<OneHandSword>>(jsonString);
             */

            ItemManager manager = ItemManager.GetInstance();

            string text = @"
EE輝石のベルト+4
腰アクセサリーレア度_A
とりどりの宝石が
さまざまな効果を
生み出すベルト
取り引き不可
Lv 1以上装備可
追加効果
輝石効果:かいふく魔力 +1%
輝石効果:エレ系に ダメージ+6.0%
輝石効果:金
秘石効果:烏系に ダメージ +6.0%
>魅了 ガード+10.0%
戦士 僧侶 魔使 武闘 盗賊 旅芸 バト パラ 魔戦 レン 賢者 スパ
まも どう 踊り 占い 天地 遊び デス
O装備できる仲間モンスターを見る
";

            Utility.AnalyzeItem(1, text, manager.GetItemData());



            manager.DownloadItemData();
        }