예제 #1
2
        private static void Process(int width, int height, MagickImage image, int? quality)
        {
            image.Strip();

            if (quality.HasValue)
            {
                image.Quality = quality.Value;
            }

            //模版的宽高比例
            var templateRate = (double)width / height;

            //原图片的宽高比例
            var nowRate = (double)image.Width / image.Height;

            if (templateRate < nowRate)
            {
                //以高为准缩放
                // Resize each image in the collection to a width of 200. When zero is specified for the height
                // the height will be calculated with the aspect ratio.
                image.Resize(0, height);
                image.ChopHorizontal(width, image.Width - width);
            }
            else
            {
                //以宽为准缩放
                image.Resize(width, 0);
                image.ChopVertical(height, image.Height - height);
            }
        }
예제 #2
1
    public void Test_Sketch()
    {
      using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
      {
        image.Resize(400, 400);

        image.Sketch();
        image.ColorType = ColorType.Bilevel;

        ColorAssert.AreEqual(MagickColors.White, image, 63, 100);
        ColorAssert.AreEqual(MagickColors.White, image, 150, 175);
      }
    }
예제 #3
1
        public void Draw(MagickImage map)
        {
            MainForm.ProgressStart("Drawing lightmap ...");

            // Get the heightmap
            MagickImage heightmap = zoneConfiguration.Heightmap.Heightmap;

            using (MagickImage lightmap = new MagickImage(Color.Transparent, 256, 256))
            {
                using (PixelCollection heightmapPixels = heightmap.GetReadOnlyPixels())
                {
                    using (WritablePixelCollection lightmapPixels = lightmap.GetWritablePixels())
                    {
                        // z-component of surface normals
                        double nz = 512d / zScale;
                        double nz_2 = nz * nz;
                        double nzlz = nz * lightVector[2];

                        int y1 = 0, y2 = 0;
                        for (int y = 0; y < lightmap.Height; y++)
                        {
                            if (y == 0) y1 = 0;
                            else y1 = y - 1;
                            if (y == 255) y2 = 255;
                            else y2 = y + 1;

                            int x1 = 0, x2 = 0;
                            for (int x = 0; x < lightmap.Width; x++)
                            {
                                if (x == 0) x1 = 0;
                                else x1 = x - 1;
                                if (x == 255) x2 = 255;
                                else x2 = x + 1;

                                double l = heightmapPixels.GetPixel(x1, y).GetChannel(0);
                                double r = heightmapPixels.GetPixel(x2, y).GetChannel(0);
                                double u = heightmapPixels.GetPixel(x, y1).GetChannel(0);
                                double d = heightmapPixels.GetPixel(x, y2).GetChannel(0);

                                double nx = l - r;
                                double ny = u - d;

                                double m_normal = Math.Sqrt(nx * nx + ny * ny + nz_2);
                                double ndotl = (nx * lightVector[0] + ny * lightVector[1] + nzlz) / m_normal;

                                double pixelValue = lightBase - ndotl * lightScale * 256d;

                                ushort pixelValueDiff = 0;
                                ushort alphaValue = ushort.MaxValue;
                                if(pixelValue < 0)
                                {
                                    pixelValueDiff = 0;
                                    alphaValue = (ushort)pixelValue;
                                }
                                else
                                {
                                    pixelValueDiff = (ushort)pixelValue;
                                }

                                // ColorDodge map
                                // white lightens areas where black does nothing
                                // alpha darkens areas
                                lightmapPixels.Set(x, y, new ushort[] { pixelValueDiff, pixelValueDiff, pixelValueDiff, alphaValue });
                            }

                            int percent = 100 * y / lightmap.Height;
                            MainForm.ProgressUpdate(percent);
                        }
                    }
                }

                MainForm.ProgressStartMarquee("Merging...");
                lightmap.Blur(0.0, 0.5);

                lightmap.VirtualPixelMethod = VirtualPixelMethod.Transparent;
                lightmap.FilterType = FilterType.Gaussian;
                lightmap.Resize(zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize);

                // Apply the bumpmap using ColorDodge
                map.Composite(lightmap, 0, 0, CompositeOperator.ColorDodge);

                MainForm.ProgressReset();
            }
        }
예제 #4
0
    public void Test_KernelProfileRecords()
    {
      OpenCLDevice device = GetEnabledDevice();
      if (device == null)
        Assert.Inconclusive("No OpenCL devices detected.");

      device.ProfileKernels = true;

      using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
      {
        image.Resize(500, 500);
        image.Resize(100, 100);
      }

      device.ProfileKernels = false;

      List<OpenCLKernelProfileRecord> records = new List<OpenCLKernelProfileRecord>(device.KernelProfileRecords);
      Assert.IsFalse(records.Count < 2);

      foreach (OpenCLKernelProfileRecord record in records)
      {
        Assert.IsNotNull(record.Name);
        Assert.IsFalse(record.Count < 0);
        Assert.IsFalse(record.MaximumDuration < 0);
        Assert.IsFalse(record.MinimumDuration < 0);
        Assert.IsFalse(record.TotalDuration < 0);

        Assert.AreEqual(record.AverageDuration, record.TotalDuration / record.Count);
      }
    }
예제 #5
0
        public static BitmapImage FastBlur(BitmapImage image, double percentage)
        {
            MagickImage magick = new MagickImage(ImageUtilities.BitmapImage2Bitmap(image));
            magick.Resize(new Percentage(50.0 / percentage));
            magick.Resize(new Percentage(200 * percentage));

            return magick.ToBitmap().ToBitmapImage();
        }
예제 #6
0
        public static Bitmap FastBlur(Uri image, double percentage)
        {
            MagickImage magick = new MagickImage(new Bitmap(image.AbsolutePath));
            magick.Resize(new Percentage(50.0 / percentage));
            magick.Resize(new Percentage(200 * percentage));

            return magick.ToBitmap();
        }
예제 #7
0
파일: ImgCov.cs 프로젝트: Centny/cswf.doc
 public override void Exec()
 {
     try
     {
         var img = new ImageMagick.MagickImage(this.AsSrc);
         img.BackgroundColor = new MagickColor(Color.White);
         if (".jpg".Equals(Path.GetExtension(this.DstF), StringComparison.OrdinalIgnoreCase))
         {
             img.HasAlpha = false;
         }
         img.Resize(this.size);
         var as_dst = String.Format(this.AsDstF, this.Beg);
         var as_dir = Path.GetDirectoryName(as_dst);
         if (!Directory.Exists(as_dir))
         {
             Directory.CreateDirectory(as_dir);
         }
         img.Write(as_dst);
         this.Result.Files.Add(String.Format(this.DstF, this.Beg));
         this.Result.Count += 1;
     }
     catch (Exception e)
     {
         this.Result.Code = 500;
         this.Fails.Add(e);
     }
 }
예제 #8
0
        /// <summary>
        /// Método que trata a imagem e copia para a pasta de saída
        /// </summary>
        /// <param name="arq">Imagem a ser editada</param>
        /// <param name="width">Define  o Width da imagem de saída</param>
        /// <param name="height">Define o height da imagem de saída</param>
        /// <param name="transparent">Identifica se deve deixar a imagem com o fundo transparent ou não</param>
        /// <returns>True - Sucesso; False - Erro</returns>
        public bool TrataImagem(FileInfo arq, int width, int height, bool transparent, ref string mensagemErro)
        {
            mensagemErro = "";
            try
            {
                ImageMagick.MagickImage img = new ImageMagick.MagickImage(arq);

                if (transparent)
                {
                    img.ColorFuzz = new Percentage(10);
                    // -transparent white
                    img.Transparent(MagickColors.White);
                }

                img.Resize(width, height);
                img.Write(caminhoSaida + "\\" + arq.Name.Replace(arq.Extension, width.ToString() + "x" + height.ToString()) + cbx_tipos.SelectedItem.ToString());

                return(true);
            }
            catch (Exception e)
            {
                mensagemErro = "Erro ao tratar a imagem " + arq.FullName + ". Erro " + e.Message;
                return(false);
            }
        }
예제 #9
0
        /// <summary>
        /// 设置图片水印,使用MagickImage.Net
        /// </summary>
        /// <param name="path">需要加载水印的图片路径(绝对路径)</param>
        /// <param name="waterpath">水印图片(绝对路径)</param>
        /// <param name="location">水印位置</param>
        /// <returns></returns>
        public static string ImageWatermarkByMagick(string path, string waterpath, ImageLocationMode location)
        {
            string extName = Path.GetExtension(path);

            if (string.IsNullOrEmpty(extName))
            {
                return(path);
            }
            extName = extName.ToLower();
            if (!(extName == ".jpg" || extName == ".bmp" || extName == ".jpeg" || extName == ".png"))
            {
                return(path);
            }
            // 读取需要水印的图片
            using (ImageMagick.MagickImage image = new ImageMagick.MagickImage(path))
            {
                // 读取水印图片
                using (ImageMagick.MagickImage watermark = new ImageMagick.MagickImage(waterpath))
                {
                    // 设置水印透明度
                    //watermark.Evaluate(Channels.Alpha, EvaluateOperator.Divide, 7);
                    // 设置绘制水印位置
                    image.Composite(watermark, GetLocation(location), CompositeOperator.Over);
                }
                image.Resize(image.Width, image.Height);
                image.Quality           = 75;
                image.CompressionMethod = ImageMagick.CompressionMethod.JPEG;
                image.Write(path);
                return(path);
            }
        }
예제 #10
0
        public static Bitmap FastBlur(Bitmap image, double percentage)
        {
            MagickImage magick = new MagickImage(image);
            magick.Resize(new Percentage(50.0 / percentage));
            magick.Resize(new Percentage(200 * percentage));

            return magick.ToBitmap();


            /*
            magick.Grayscale(ImageMagick.PixelIntensityMethod.Average);
            MagickImage temp = new MagickImage(Game.Instance.ResourceController.BuildPath(@"..\..\Global Resources\Assets\Images\black_50alpha.png"));
            temp.Alpha(AlphaOption.Activate);
            temp.Resize(magick.Width * 2, magick.Height * 2);
            magick.Composite(temp, CompositeOperator.Darken);
            */
        }
예제 #11
0
 public void ResizePng(PngFileInfo sourcePngFile, PngFileInfo targetPngFile)
 {
     _logger.InfoFormat("Resizing: {0} -> {1}", sourcePngFile.Name, targetPngFile.Name);
     var sourcePngFileInfo = new FileInfo(sourcePngFile.FullName);
     using (var sourceImage = new MagickImage(sourcePngFileInfo))
     {
         sourceImage.Resize(targetPngFile.Size, targetPngFile.Size);
         var targetPngFileInfo = new FileInfo(targetPngFile.FullName);
         sourceImage.Write(targetPngFileInfo);
     }
 }
        // Not so useful
        public static void MakeThumbnailWithExif(this MagickImage image, Size size)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            if (size == null)
            {
                throw new ArgumentNullException(nameof(size));
            }

            image.Resize(size.Width, size.Height);
        }
예제 #13
0
        public string Execute(FileItem fileItem,string infile, string dest, ValuePairEnumerator configData)
        {
            var conf = new ResizeTransformViewModel(configData);
            dest = Path.Combine(Path.GetDirectoryName(dest), Path.GetFileNameWithoutExtension(dest) + ".jpg");
            using (MagickImage image = new MagickImage(infile))
            {
                MagickGeometry geometry = new MagickGeometry(conf.Width, conf.Height);
                geometry.IgnoreAspectRatio = !conf.KeepAspect;

                image.Resize(geometry);
                image.Format = MagickFormat.Jpeg;
                image.Write(dest);
            }
            return dest;
        }
예제 #14
0
    public static void ResizeToFixedSize()
    {
      // Read from file
      using (MagickImage image = new MagickImage(SampleFiles.SnakewarePng))
      {
        MagickGeometry size = new MagickGeometry(100, 100);
        // This will resize the image to a fixed size without maintaining the aspect ratio.
        // Normally an image will be resized to fit inside the specified size.
        size.IgnoreAspectRatio = true;

        image.Resize(size);

        // Save the result
        image.Write(SampleFiles.OutputDirectory + "Snakeware.100x100.png");
      }
    }
예제 #15
0
        public Uri ResizeImageByLengthOfLongestSide(Uri imageToResizeUri)
        {
            var fileName = Path.GetFileName(imageToResizeUri.LocalPath);

            var magicImage = new MagickImage(Path.Combine(_fileStorageSettings.ImageStorageFolder, fileName));

            var size = magicImage.Height >= magicImage.Width
                ? new MagickGeometry(_lengthOfLongestSideOfResized, 0)
                : new MagickGeometry(0, _lengthOfLongestSideOfResized);

            size.IgnoreAspectRatio = false;

            magicImage.Resize(size);

            var newName = GenerateRandomFileName(magicImage.FileName);
            var pathOfNewImage = Path.Combine(_fileStorageSettings.ImageStorageFolder, newName);
            magicImage.Write(pathOfNewImage);

            return new Uri($"{_applicationLocationSettings.BackendAdress}/image/" + newName);
        }
예제 #16
0
        public string Execute(FileItem item, string infile, string dest, ValuePairEnumerator configData)
        {
            var conf = new PixelBinningViewModel(configData);
            dest = Path.Combine(Path.GetDirectoryName(dest), Path.GetFileNameWithoutExtension(dest) + ".jpg");

            using (MagickImage image = new MagickImage(infile))
            {
                int newx = image.Width/(conf.SelectedMode + 2);
                int newy = image.Height / (conf.SelectedMode + 2);
                int cropx = newx * (conf.SelectedMode + 2);
                int cropy = newy * (conf.SelectedMode + 2);
                if (cropx != image.Width || cropy != image.Height)
                    image.Crop(cropx, cropy, Gravity.Center);
                image.FilterType = FilterType.Box;
                image.Resize(newx,newy);
                image.Format = MagickFormat.Jpeg;
                image.Write(dest);
            }
            return dest;
        }
예제 #17
0
    public void Test_Unregister()
    {
      using (MagickImage image = new MagickImage(Files.SnakewarePNG))
      {
        using (MemoryStream memoryStream = new MemoryStream())
        {
          image.Resize(256, 256);
          image.Format = MagickFormat.Ico;
          image.Write(memoryStream);
          memoryStream.Position = 0;

          MagickFormatInfo formatInfo = MagickNET.GetFormatInformation(MagickFormat.Ico);
          Assert.IsNotNull(formatInfo);
          Assert.IsTrue(formatInfo.Unregister());

          ExceptionAssert.Throws<MagickMissingDelegateErrorException>(delegate ()
          {
            new MagickImage(memoryStream);
          });
        }
      }
    }
예제 #18
0
        public ActionResult ProductEdit(Product product, HttpPostedFileBase ImgFile)
        {
            var Product = db.Product.Where(m => m.ProductID == product.ProductID).FirstOrDefault();
            //驗證檔案
            ImgUploadValidate ImgV = new ImgUploadValidate();

            ImgV.filesize = 2000; //限制2mb
            if (ImgV.UploadUserFile(ImgFile) || ImgV.ErrorMessage == "檔案不能為空的")
            {                     //檔案驗證成功
                if (ImgV.UploadUserFile(ImgFile))
                {
                    //local

                    string fileName = product.ProductID + ImgV.contentType;
                    var    path     = Path.Combine(Server.MapPath("~/Image"), fileName);
                    ImgFile.SaveAs(path);
                    product.ProductImg = "~/Image/" + fileName;

                    //compress
                    using (ImageMagick.MagickImage oImage = new ImageMagick.MagickImage(path))
                    {
                        oImage.Format     = MagickFormat.Jpg;
                        oImage.ColorSpace = ImageMagick.ColorSpace.sRGB; //色盤採用sRGB
                        oImage.Quality    = 80;                          //壓縮率
                        if (oImage.Height < 200)
                        {
                            oImage.Resize(0, 200);
                        }
                        oImage.Strip(); //去除圖片profile
                        oImage.Write(path);
                    }

                    //db
                    byte[] FileBytes;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        ImgFile.InputStream.CopyTo(ms);
                        FileBytes = ms.GetBuffer();
                    }
                    Product.ProductImg_DB = FileBytes;
                    Product.ProductImg    = "~/Image/" + fileName;
                }
                Product.Modify_Date    = DateTime.Now;
                Product.ProductExplain = product.ProductExplain;
                Product.ProductName    = product.ProductName;
                Product.ProductPrice   = product.ProductPrice;
                Product.Shelf_Flag     = product.Shelf_Flag;
                Product.CategoryID     = product.CategoryID;

                try
                {
                    if (ModelState.IsValid)
                    {   //model驗證成功
                        db.SaveChanges();
                        TempData["EditMessage"] = product.ProductID + "更新成功!";
                        return(RedirectToAction("ProductList"));
                    }
                    else
                    {   //model驗證失敗
                        TempData["EditMessage"] = "更新失敗,請確認資料格式是否正確!!";
                        return(View(Product));
                    }
                }
                catch (Exception ex)
                {   //資料庫例外狀況
                    logger.Error(ex.Message);
                    TempData["EditMessage"] = ex.Message;
                    return(View(Product));
                }
                //return RedirectToAction("ProductList");
            }
            else
            {   //檔案驗證失敗
                TempData["EditMessage"] = ImgV.ErrorMessage;
                return(View(Product));
            }
        }
예제 #19
0
        private void GenerateHeightmap()
        {
            if(this.heightmapGenerated) return;
            MainForm.ProgressStart("Processing heightmap ...");

            using (MagickImage offsetmap = zoneConfiguration.GetOffsetMap())
            {
                using (MagickImage terrainmap = zoneConfiguration.GetTerrainMap())
                {
                    m_heightmap = new MagickImage(Color.Black, offsetmap.Width, offsetmap.Height);

                    using (WritablePixelCollection heightmapPixels = m_heightmap.GetWritablePixels())
                    {
                        PixelCollection terrainPixels = terrainmap.GetReadOnlyPixels();
                        PixelCollection offsetPixels = offsetmap.GetReadOnlyPixels();

                        for (int x = 0; x < offsetmap.Width; x++)
                        {
                            for (int y = 0; y < offsetmap.Height; y++)
                            {
                                ushort terrainPixelValue = (ushort)(terrainPixels[x, y].GetChannel(0) / 256);
                                ushort offsetPixelValue = (ushort)(offsetPixels[x, y].GetChannel(0) / 256);
                                ushort heightmapPixelValue = (ushort)(terrainPixelValue * m_terrainfactor + offsetPixelValue * m_offsetfactor);

                                heightmapPixels.Set(x, y, new ushort[] { heightmapPixelValue, heightmapPixelValue, heightmapPixelValue });
                            }

                            int percent = 100 * x / offsetmap.Width;
                            MainForm.ProgressUpdate(percent);
                        }

                        heightmapPixels.Write();
                    }

                    MainForm.ProgressStartMarquee("Merging ...");

                    m_heightmap.Quality = 100;
                    m_heightmap.Write(m_heightmapFile.FullName);

                    // Scale to target size
                    m_heightmapScaled = new MagickImage(m_heightmap);
                    m_heightmapScaled.Resize(zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize);
                }
            }

            this.heightmapGenerated = true;
            MainForm.ProgressReset();
        }
예제 #20
0
        public ActionResult CreateProduct(HttpPostedFileBase ImgFile, Product cProduct, string base64str)
        {
            //驗證檔案
            ImgUploadValidate ImgV = new ImgUploadValidate();

            ImgV.filesize = 2000; //限制2mb
            if (ImgV.UploadUserFile(ImgFile))
            {                     //檔案驗證成功
                //local
                string fileName = cProduct.ProductID + ImgV.contentType;
                var    path     = Path.Combine(Server.MapPath("~/Image"), fileName);
                ImgFile.SaveAs(path);
                cProduct.ProductImg = "~/Image/" + fileName;

                //compress
                using (ImageMagick.MagickImage oImage = new ImageMagick.MagickImage(path))
                {
                    oImage.Format     = MagickFormat.Jpg;
                    oImage.ColorSpace = ImageMagick.ColorSpace.sRGB; //色盤採用sRGB
                    oImage.Quality    = 80;                          //壓縮率
                    if (oImage.Height < 200)
                    {
                        oImage.Resize(0, 200);
                    }
                    oImage.Strip(); //去除圖片profile
                    oImage.Write(path);
                }
                //db
                byte[] FileBytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    ImgFile.InputStream.CopyTo(ms);
                    FileBytes = ms.GetBuffer();
                }
                cProduct.ProductImg_DB = FileBytes;
                cProduct.Create_Date   = DateTime.Now;
                cProduct.Delete_Flag   = false;
                cProduct.Shelf_Flag    = true;
                if (ModelState.IsValid)
                {                                                                    //model驗證成功
                    if (db.Product.Any(p => p.ProductID.Equals(cProduct.ProductID))) //判斷資料是否重複
                    {
                        TempData["DBResultErrorMessage"] = cProduct.ProductID + "資料已重複,請重新輸入";
                        return(View("CreateProduct"));
                    }
                    try
                    {
                        db.Product.Add(cProduct);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {//資料庫異動例外狀況
                        logger.Error(ex.Message);
                        TempData["DBResultErrorMessage"] = ex.Message;
                        return(View("CreateProduct"));
                    }
                    TempData["DBResultErrorMessage"] = cProduct.ProductID + "新增成功!";
                    return(RedirectToAction("ProductList"));    //新增成功
                }
                else
                {   //model 驗證失敗
                    return(View("CreateProduct"));
                }
            }
            else
            {//檔案驗證失敗
                TempData["ImgValidate"] = ImgV.ErrorMessage;
                return(View("CreateProduct"));
            }
        }
예제 #21
0
    public void Test_Extent()
    {
      using (MagickImage image = new MagickImage())
      {
        image.Read(Files.RedPNG);
        image.Resize(new MagickGeometry(100, 100));
        Assert.AreEqual(100, image.Width);
        Assert.AreEqual(33, image.Height);

        image.BackgroundColor = MagickColor.Transparent;
        image.Extent(100, 100, Gravity.Center);
        Assert.AreEqual(100, image.Width);
        Assert.AreEqual(100, image.Height);

        Test_Pixel_Equal(image, 0, 0, MagickColor.Transparent);
      }
    }
예제 #22
0
        public static void ApplyPreviewImageMagick(string source, string destination, double maxWidth = 0d, double maxHeight = 0d) {
            using (var image = new MagickImage(source)) {
                if (maxWidth > 0d || maxHeight > 0d) {
                    var k = Math.Max(maxHeight / image.Height, maxWidth / image.Width);
                    image.Interpolate = PixelInterpolateMethod.Bicubic;
                    image.FilterType = FilterType.Lanczos;
                    image.Sharpen();
                    image.Resize((int)(k * image.Width), (int)(k * image.Height));
                    image.Crop(CommonAcConsts.PreviewWidth, CommonAcConsts.PreviewHeight, Gravity.Center);
                }

                image.Quality = 95;
                image.Density = new MagickGeometry(96, 96);
                if (File.Exists(destination)) {
                    try {
                        File.Delete(destination);
                    } catch (UnauthorizedAccessException) {
                        Thread.Sleep(200);
                        File.Delete(destination);
                    }
                }

                image.Write(destination);
            }
        }
예제 #23
0
        public bool OverrideTextureMaps(string textureName, double reflection, double blur, double specular) {
            using (var image = new MagickImage(Kn5.TexturesData[textureName])) {
                if (image.Width > 512 || image.Height > 512) {
                    image.Resize(512, 512);
                }

                image.BrightnessContrast(reflection, 1d, Channels.Red);
                image.BrightnessContrast(blur, 1d, Channels.Green);
                image.BrightnessContrast(specular, 1d, Channels.Blue);

                return OverrideTexture(textureName, image.ToByteArray(MagickFormat.Bmp));
            }
        }
예제 #24
0
        public MagickImage Draw()
        {
            MainForm.ProgressStart("Rendering background ...");

            // Check which terrain file is used
            string texMpk = string.Format("{0}\\tex{1}.mpk", this.textureZoneDataDirectory, this.textureZoneId);
            string lodMpk = string.Format("{0}\\lod{1}.mpk", this.textureZoneDataDirectory, this.textureZoneId);

            // Get the tile dimension
            double tileWidth = 512.0;
            string tileTemplate = "";

            MPAK mpak = new MPAK();
            if (File.Exists(texMpk))
            {
                mpak.Load(texMpk);

                if (mpak.Files.Where(f => f.Name.ToLower() == "tex00-00.dds").Count() > 0)
                {
                    tileTemplate += "tex0{0}-0{1}.dds";
                    tileWidth = 512.0;
                }
            }

            if (string.IsNullOrEmpty(tileTemplate))
            {
                mpak.Load(lodMpk);

                if (mpak.Files.Where(f => f.Name.ToLower() == "lod00-00.dds").Count() > 0)
                {
                    tileTemplate += "lod0{0}-0{1}.dds";
                    tileWidth = 256.0;
                }
            }

            if (string.IsNullOrEmpty(tileTemplate))
            {
                MainForm.Log(string.Format("Zone {0}: No background textures found!", zoneConfiguration.ZoneId), MainForm.LogLevel.error);
                return null;
            }

            // original size
            double orginalWidth = tileWidth * 8;
            double resizeFactor = (double)zoneConfiguration.TargetMapSize / (double)orginalWidth; // 0 - 1

            MagickImage map = new MagickImage(Color.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize);

            int lastWidth = 0;
            int x = 0;
            for (int col = 0; col <= 7; col++)
            {
                int y = 0;
                for (int row = 0; row <= 7; row++)
                {
                    string filename = string.Format(tileTemplate, col, row);

                    using (MagickImage mapTile = new MagickImage(mpak.GetFile(filename).Data))
                    {
                        int newSize = Convert.ToInt32(mapTile.Width * resizeFactor);
                        mapTile.Resize(newSize, newSize);

                        map.Composite(mapTile, x, y, CompositeOperator.SrcOver);

                        // Calculate new y
                        y += mapTile.Height;
                        lastWidth = mapTile.Height;
                    }
                }

                x += lastWidth;

                int percent = 100 * col / 8;
                MainForm.ProgressUpdate(percent);
            }

            MainForm.ProgressStartMarquee("Merging ...");

            // Remove rounding fails
            map.Trim();

            // Flip if set
            if (this.flipX) map.Flop();
            if (this.flipY) map.Flip();

            // Sharpen (tested a lot, seems to be the best values)
            map.Sharpen(4, 3);

            MainForm.ProgressReset();

            return map;
        }
예제 #25
0
        private void DisplayRezisedImage(string file, Actions caseDirectory)
        {
            //put this in a background worker.
            try
            {
                using (MagickImage image = new MagickImage(Path.Combine(Constants.ContainerLocation, Constants.Directories.GetSpecifiedCaseDirectory(caseDirectory), file)))
                {
                    MagickGeometry size = new MagickGeometry(196, 196);
                    size.IgnoreAspectRatio = false;
                    image.Resize(size);
                    this.InvokeIfRequired(() => FilePreviewImage.Image = image.ToBitmap());
                }

          
            }
            catch(Exception e)
            {
                DisplayFileIconWithFileSize(file, caseDirectory);
            }
        }
        public IHttpActionResult DownloadInstaPhotos()
        {
            QpiroJSON resp = new QpiroJSON();

            try
            {
                string[] file = Directory.GetFiles(UserProperty.Current_User, UserProperty.UserXmlInfo);

                if (file.Count() != 1)
                    throw new Exception("Geçersiz kullanıcı bilgileri.");

                string _range = "0-1000";// ilk kaç resim ?
                int min = int.Parse(_range.Split('-')[0]);
                int max = int.Parse(_range.Split('-')[1]);

                XDocument doc = XDocument.Load(file[0]);
                XElement root = doc.Elements("_" + ImageProperty.GetUserName()).First();
                XElement InstagramP = root.Elements("InstagramPhotos").FirstOrDefault();
                List<XElement> potos = InstagramP.Elements("Photos").ToList();
                //download
                List<string> imglist = InstagramProfile.UserPhotos();

                ServerAsyncCallBack servers = new ServerAsyncCallBack();
                servers.Execute(Api._QPR.Type.AsyncCallType.DownloadInstaPhotos, imglist);

                if (imglist.Count > 0)
                {
                    //https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s150x150/e15/
                    for (int i = 0; i < imglist.Count; i++)
                    {
                        if (i >= min && i <= max)
                        {
                            //resp.Data.Add(imglist[i]);
                            string filname = Path.GetFileName(imglist[i]);
                            if (potos.FindIndex(p => Path.GetFileName(p.Value) == filname) == -1)
                            {
                                XElement photo = new XElement("Photos",
                                    new XAttribute("useThis", true.ToString())
                                    );
                                photo.Value = imglist[i];
                                InstagramP.Add(photo);

                                using (MagickImage mini = new MagickImage(InstagramProfile.DownloadImage(imglist[i])))
                                {
                                    mini.Quality = 100;
                                    mini.Resize(94, 94);

                                    mini.Write(Path.Combine(UserProperty.Data_InstagramPhotos, filname));
                                    mini.Dispose();
                                }
                            }
                        }
                    }
                    doc.Save(file[0]);
                    resp.Data.Add("Resimler Güncellendi");
                }
                else
                {
                    throw new Exception("Instagram hesabınızda hiç fotoğrafınız bulunmuyor");
                }
                InstagramP = null;
                potos.Clear();
                imglist.Clear();
            }
            catch (Exception e)
            {
                resp.Message = e.Message;
            }
            return this.Json<QpiroJSON>(resp);
        }
예제 #27
0
        private void DrawTree(MagickImage overlay, DrawableFixture fixture)
        {
            System.Drawing.Color testColor = System.Drawing.ColorTranslator.FromHtml("#5e683a");

            using (MagickImage pattern = new MagickImage(MagickColor.Transparent, fixture.CanvasWidth, fixture.CanvasHeight))
            {
                using (MagickImage patternTexture = new MagickImage(string.Format("{0}\\data\\textures\\{1}.png", System.Windows.Forms.Application.StartupPath, "leaves_mask")))
                {
                    patternTexture.Resize(fixture.CanvasWidth / 2, fixture.CanvasHeight / 2);
                    pattern.Texture(patternTexture);

                    Random rnd = new Random();
                    pattern.Rotate(rnd.Next(0, 360));

                    using (MagickImage modelCanvas = new MagickImage(MagickColor.Transparent, fixture.CanvasWidth, fixture.CanvasHeight))
                    {
                        foreach (DrawableElement drawableElement in fixture.DrawableElements)
                        {
                            DrawablePolygon polyDraw = new DrawablePolygon(drawableElement.coordinates);

                            // A Shaded model without lightning is not shaded... but just we add this just be flexible
                            if (fixture.RendererConf.HasLight)
                            {
                                float r, g, b, light;

                                light = (float)drawableElement.lightning * 2f;
                                r = fixture.Tree.AverageColor.R * light;
                                g = fixture.Tree.AverageColor.G * light;
                                b = fixture.Tree.AverageColor.B * light;

                                modelCanvas.FillColor = new MagickColor(
                                    Convert.ToUInt16(r * 255),
                                    Convert.ToUInt16(g * 255),
                                    Convert.ToUInt16(b * 255)
                                );
                            }
                            else
                            {
                                modelCanvas.FillColor = fixture.RendererConf.Color;
                            }

                            modelCanvas.Draw(polyDraw);
                        }

                        // Add leaves pattern
                        pattern.Composite(modelCanvas, Gravity.Center, CompositeOperator.DstIn);
                        modelCanvas.Composite(pattern, Gravity.Center, CompositeOperator.CopyAlpha);

                        if (fixture.RendererConf.HasShadow)
                        {
                            modelCanvas.BorderColor = MagickColor.Transparent;
                            modelCanvas.Border((int)fixture.RendererConf.ShadowSize);
                            modelCanvas.Shadow(
                                fixture.RendererConf.ShadowOffsetX,
                                fixture.RendererConf.ShadowOffsetY,
                                fixture.RendererConf.ShadowSize,
                                new Percentage(100 - fixture.RendererConf.ShadowTransparency),
                                fixture.RendererConf.ShadowColor
                            );

                            // Update the canvas position to match the new border
                            fixture.CanvasX -= fixture.RendererConf.ShadowSize;
                            fixture.CanvasY -= fixture.RendererConf.ShadowSize;
                        }

                        if (fixture.RendererConf.Transparency != 0)
                        {
                            modelCanvas.Alpha(AlphaOption.Set);

                            double divideValue = 100.0 / (100.0 - fixture.RendererConf.Transparency);
                            modelCanvas.Evaluate(Channels.Alpha, EvaluateOperator.Divide, divideValue);
                        }

                        overlay.Composite(modelCanvas, Convert.ToInt32(fixture.CanvasX), Convert.ToInt32(fixture.CanvasY), CompositeOperator.SrcOver);
                    }
                }
            }
        }
 public void UploadResource()
 {
     if (HttpContext.Current.Request.Files.AllKeys.Any())
     {
         try
         {
             HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files["file"];
             string fileExt = Path.GetExtension(httpPostedFile.FileName).ToLower();
             if (fileExt != ".jpg" || (httpPostedFile.ContentLength / 1024) > 12192)
                 throw new Exception("Dosya uzantısı geçerli değil veya boyut 12mb dan büyük.");
             string SaveFileDir = "";
             string randomhexnum = "";
             do
             {
                 randomhexnum = "1" + ImageProperty.GenerateRandomHexNumber(6) + "a";
                 SaveFileDir = Path.Combine(UserProperty.ResourcePhotos_Path, randomhexnum + fileExt);
             }
             while (File.Exists(SaveFileDir));
             using (MagickImage imagem = new MagickImage(httpPostedFile.InputStream))
             {
                 int yuzde = 50;
                 imagem.Quality = 100;
                 int _w = imagem.Width + (imagem.Width / 100) * yuzde;
                 int _h = imagem.Height + (imagem.Height / 100) * yuzde;
                 imagem.Resize(_w, _h);
                 imagem.Write(SaveFileDir);
             }
         }
         catch (Exception e)
         {
             throw new Exception(e.Message);
         }
     }
 }
예제 #29
0
        public ActionResult CreateProduct(HttpPostedFileBase ImgFile, Product cProduct, string base64str)
        {
            if (ImgFile != null && ImgFile.ContentLength > 0)
            {
                //local
                string str  = "";
                string type = ImgFile.ContentType;
                if (ImgFile.ContentType == "image/jpg")
                {
                    str = ".jpg";
                }
                else if (ImgFile.ContentType == "image/jpeg")
                {
                    str = ".jpeg";
                }
                else if (ImgFile.ContentType == "image/png")
                {
                    str = ".png";
                }
                string fileName = cProduct.ProductID + str;
                var    path     = Path.Combine(Server.MapPath("~/Image"), fileName);
                ImgFile.SaveAs(path);
                cProduct.ProductImg = "~/Image/" + fileName;

                //compress
                using (ImageMagick.MagickImage oImage = new ImageMagick.MagickImage(path))
                {
                    oImage.Format     = ImageMagick.MagickFormat.Jpg;
                    oImage.ColorSpace = ImageMagick.ColorSpace.sRGB; //色盤採用sRGB
                    oImage.Quality    = 80;                          //壓縮率
                    oImage.Resize(200, 0);
                    oImage.Strip();
                    oImage.Write(path);
                }
                //db
                byte[] FileBytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    ImgFile.InputStream.CopyTo(ms);
                    FileBytes = ms.GetBuffer();
                }
                cProduct.ProductImg_DB = FileBytes;
            }
            cProduct.Create_Date = DateTime.Now;
            cProduct.Delete_Flag = false;
            if (ModelState.IsValid)
            {
                if (db.Product.Any(p => p.ProductID.Equals(cProduct.ProductID)))    //判斷資料是否重複
                {
                    ViewBag.DBResultErrorMessage = cProduct.ProductID + "資料已重複";
                    return(View("CreateProduct", Session["UserTag"].ToString()));
                }
                try
                {
                    db.Product.Add(cProduct);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                    ViewBag.DBResultErrorMessage = ex.Message;
                    return(View("CreateProduct", Session["UserTag"].ToString()));
                }

                ViewBag.DBResultErrorMessage = cProduct.ProductID + "新增成功!";
            }

            return(View("CreateProduct", Session["UserTag"].ToString()));
        }
예제 #30
0
        public void CopyFile(string filename, string destFile)
        {
            using (MagickImage image = new MagickImage(filename))
            {
                double zw = (double)Width / image.Width;
                double zh = (double)Height /image.Height;
                double za = FillImage ? ((zw <= zh) ? zw : zh) : ((zw >= zh) ? zw : zh);

                if (FillImage)
                {
                    double aspect = (double) VideoType.Width/VideoType.Height;
                    double pAspect = (double) image.Width/image.Height;
                    if (aspect > pAspect)
                        image.Crop(image.Width, (int) (image.Width/aspect), Gravity.Center);
                    else
                        image.Crop((int) (image.Height/aspect), image.Height, Gravity.Center);
                }

                MagickGeometry geometry = new MagickGeometry(VideoType.Width, VideoType.Height)
                {
                    IgnoreAspectRatio = false,
                    FillArea = false
                };

                image.FilterType = FilterType.Point;
                image.Resize(geometry);
                image.Quality = 80;
                image.Format = MagickFormat.Jpeg;
                image.Write(destFile);
            }
        }
예제 #31
0
        public MagickImage GetWateryTexture()
        {
            if (m_waterTexture != null) return m_waterTexture;

            string textureFile = string.Format("{0}\\data\\textures\\watery.dds", System.Windows.Forms.Application.StartupPath);

            MagickImage tex = new MagickImage(textureFile);
            tex.ColorSpace = ColorSpace.Gray;
            double texResize = (1 - 256.0 / zoneConfiguration.TargetMapSize) * (zoneConfiguration.TargetMapSize * 0.0001);
            if (texResize < 0) texResize = 0.1;
            tex.Resize(new Percentage(texResize));

            m_waterTexture = tex;
            return m_waterTexture;
        }
예제 #32
0
        public static List<string> PointGenerator(string inputBitmapPath, PixFormat _pixFor)
        {
            List<string> imglist = new List<string>();
            try
            {
                if (_pixFor == PixFormat._null)
                    throw new Exception("Format null olamaz") { Source = "" };

                using (MagickImage imagem = new MagickImage(inputBitmapPath))
                {
                    //############# ResizeImage #############
                    int yuzde = 100;
                    imagem.Quality = 100;
                    int _w = imagem.Width + (imagem.Width / 100) * yuzde;
                    int _h = imagem.Height + (imagem.Height / 100) * yuzde;
                    int new_W = _w - (_w % (int)_pixFor);
                    int new_H = _h - (_h % (int)_pixFor);
                    imagem.Resize(new_W, new_H);
                    imagem.Blur(5, 5);
                    //############# GenerateSquare #############
                    /////////// calculate image point rgb avg   ////////////
                    string curImgPth = Path.GetFileName(inputBitmapPath);
                    string path = UserProperty.PixelXmlMap_Path + "\\" + curImgPth.Substring(0, curImgPth.Length - 4) + _pixFor.ToString() + "_.xml";
                    FileInfo finf = new FileInfo(path);
                    List<ImgSquare> sp0 = new List<ImgSquare>();
                    if (!File.Exists(path))
                    {
                        int[,] pixavg = new int[5, 3];
                        int _pixformat = (int)_pixFor;
                        WritablePixelCollection _totalpix = imagem.GetWritablePixels(0, 0, imagem.Width, imagem.Height);
                        int range = _pixformat / 2;
                        for (int w = 0; w < imagem.Width; w += _pixformat)
                        {
                            for (int h = 0; h < imagem.Height; h += _pixformat)
                            {
                                if (!(w + _pixformat <= imagem.Width && h + _pixformat <= imagem.Height))
                                    continue;//olmazda olursa diye
                                pixavg = new int[5, 3];
                                for (int x = 0; x < range; x++)
                                {
                                    for (int y = 0; y < range; y++)
                                    {
                                        Color a = _totalpix.GetPixel(x + w + 0, h + 0 + y).ToColor().ToColor();
                                        pixavg[0, 0] += a.R;
                                        pixavg[0, 1] += a.G;
                                        pixavg[0, 2] += a.B;

                                        Color b = _totalpix.GetPixel(x + w + range, h + y).ToColor().ToColor();
                                        pixavg[1, 0] += b.R;
                                        pixavg[1, 1] += b.G;
                                        pixavg[1, 2] += b.B;

                                        Color c = _totalpix.GetPixel(x + w, h + range + y).ToColor().ToColor();
                                        pixavg[2, 0] += c.R;
                                        pixavg[2, 1] += c.G;
                                        pixavg[2, 2] += c.B;

                                        Color d = _totalpix.GetPixel(x + w + range, h + range + y).ToColor().ToColor();
                                        pixavg[3, 0] += d.R;
                                        pixavg[3, 1] += d.G;
                                        pixavg[3, 2] += d.B;
                                    }
                                }

                                //tümü için aynı toplanıyor
                                pixavg[4, 0] = pixavg[0, 0] + pixavg[1, 0] + pixavg[2, 0] + pixavg[3, 0];
                                pixavg[4, 1] = pixavg[0, 1] + pixavg[1, 1] + pixavg[2, 1] + pixavg[3, 1];
                                pixavg[4, 2] = pixavg[0, 2] + pixavg[1, 2] + pixavg[2, 2] + pixavg[3, 2];
                                //----

                                int totalminiPix = (range * range);
                                pixavg[0, 0] /= totalminiPix;
                                pixavg[0, 1] /= totalminiPix;
                                pixavg[0, 2] /= totalminiPix;

                                pixavg[1, 0] /= totalminiPix;
                                pixavg[1, 1] /= totalminiPix;
                                pixavg[1, 2] /= totalminiPix;

                                pixavg[2, 0] /= totalminiPix;
                                pixavg[2, 1] /= totalminiPix;
                                pixavg[2, 2] /= totalminiPix;

                                pixavg[3, 0] /= totalminiPix;
                                pixavg[3, 1] /= totalminiPix;
                                pixavg[3, 2] /= totalminiPix;


                                int totalPix = totalminiPix * 4;
                                pixavg[4, 0] /= totalPix;
                                pixavg[4, 1] /= totalPix;
                                pixavg[4, 2] /= totalPix;

                                sp0.Add(new ImgSquare(w, h, new List<QuardPixAvg>() 
                            {
                                new QuardPixAvg(Color.FromArgb((pixavg[0, 0]), (pixavg[0, 1]), (pixavg[0, 2])), QuardBolum.SolUst),
                                new QuardPixAvg (Color.FromArgb((pixavg[1, 0]), (pixavg[1, 1]), (pixavg[1, 2])), QuardBolum.SagUst),
                                new QuardPixAvg(Color.FromArgb((pixavg[2, 0]), (pixavg[2, 1]), (pixavg[2, 2])), QuardBolum.SolAlt),
                                new QuardPixAvg(Color.FromArgb((pixavg[3, 0]), (pixavg[3, 1]), (pixavg[3, 2])), QuardBolum.SagAlt),
                                new QuardPixAvg(Color.FromArgb((pixavg[4, 0]), (pixavg[4, 1]), (pixavg[4, 2])), QuardBolum.TotalAvg)
                            }));
                            }
                        }
                        _totalpix = null;
                        pixavg = null;
                        ////////////////////////////// xml generate ///////////////////////////////
                        #region xml oluşturma
                        //XmlDocument doc = new XmlDocument();
                        //XmlElement root = doc.CreateElement("SquarePoints");
                        //root.SetAttribute("Count", sp0.Count.ToString());
                        //root.SetAttribute("PixFormat", _pixFor.ToString());
                        //foreach (ImgSquare item in sp0)
                        //{
                        //    XmlElement child = doc.CreateElement("SquarePoint");
                        //    child.SetAttribute("WxH", item.ToString());
                        //    child.SetAttribute("ColorAVG", item.SAvgArb.ToString());
                        //    List<QuardPixAvg> lstQ = item.QuardAvg;
                        //    child.SetAttribute("SolUst", lstQ[0].QuardAvg.ToString());
                        //    child.SetAttribute("SagUst", lstQ[1].QuardAvg.ToString());
                        //    child.SetAttribute("SolAlt", lstQ[2].QuardAvg.ToString());
                        //    child.SetAttribute("SagAlt", lstQ[3].QuardAvg.ToString());
                        //    root.AppendChild(child);
                        //}
                        //doc.AppendChild(root);
                        //if (!Directory.Exists(finf.Directory.FullName))
                        //    Directory.CreateDirectory(finf.Directory.FullName);
                        //doc.Save(path);
                        //doc = null;
                        #endregion
                    }
                    else
                    {
                        #region xml okuma
                        //XmlDocument doc = new XmlDocument();
                        //doc.Load(path);
                        //XmlNodeList root1 = doc.GetElementsByTagName("SquarePoints");
                        //XmlNode root2 = root1.Item(0);
                        //foreach (XmlNode item in root2.ChildNodes)
                        //{
                        //    try
                        //    {
                        //        XmlAttribute at1 = item.Attributes[0];
                        //        string[] point = at1.InnerText.Split('x');
                        //        XmlAttribute at2 = item.Attributes[1];
                        //        string ColorAvg = at2.InnerText;
                        //        List<QuardPixAvg> lQuard = new List<QuardPixAvg>();
                        //        int SolUst = int.Parse(item.Attributes[2].InnerText);
                        //        int SagUst = int.Parse(item.Attributes[3].InnerText);
                        //        int SolAlt = int.Parse(item.Attributes[4].InnerText);
                        //        int SagAlt = int.Parse(item.Attributes[5].InnerText);
                        //        int Tumu = int.Parse(item.Attributes[1].InnerText);
                        //        lQuard.Add(new QuardPixAvg(Color.FromArgb(SolUst), QuardBolum.SolUst));
                        //        lQuard.Add(new QuardPixAvg(Color.FromArgb(SagUst), QuardBolum.SagUst));
                        //        lQuard.Add(new QuardPixAvg(Color.FromArgb(SolAlt), QuardBolum.SolAlt));
                        //        lQuard.Add(new QuardPixAvg(Color.FromArgb(SagAlt), QuardBolum.SagAlt));
                        //        lQuard.Add(new QuardPixAvg(Color.FromArgb(Tumu), QuardBolum.Tumu));
                        //        sp0.Add(new ImgSquare(int.Parse(point[0]), int.Parse(point[1]), lQuard));
                        //    }
                        //    catch (Exception e)
                        //    {
                        //        throw e;
                        //    }
                        //}
                        //root2 = null;
                        //root1 = null;
                        //doc = null;
                        #endregion
                    }
                    //#---------------------------------
                    int opacity = 50;
                    switch (_pixFor)
                    {
                        case PixFormat._null:
                            sp0.Clear();
                            throw new Exception("Tanımsız format") { Source = "" };
                            break;
                        case PixFormat._12x12: //12:36 sn
                            opacity = 50;
                            break;
                        case PixFormat._20x20: //3:10 sn
                            opacity = 50;
                            break;
                        case PixFormat._36x36: //0:50 sn
                            opacity = 50;
                            break;
                        case PixFormat._48x48: //0:27 sn
                            opacity = 50;
                            break;
                        case PixFormat._64x64: //0:15 sn
                            opacity = 50;
                            break;
                        case PixFormat._94x94: //0:08 sn
                            opacity = 50;
                            break;
                    }
                    //string MiniPicturePath = Path.Combine(UserProperty.Data_Path, PixFormat._94x94.ToString());  //eski yükleme şekli
                    string MiniPicturePath = Path.Combine(UserProperty.Data_InstagramPhotos);
                    if (Directory.Exists(MiniPicturePath))
                    {
                        Bitmap btm = imagem.ToBitmap();
                        using (Graphics gr1 = Graphics.FromImage(btm))
                        {
                            //string[] list = Directory.GetFiles(MiniPicturePath, "*" + JPG);
                            //string[] list = new string[0];
                            ///////////////////////////////////////////////////////////////
                            string[] file = Directory.GetFiles(UserProperty.Current_User, UserProperty.UserXmlInfo);

                            if (file.Count() != 1)
                                throw new Exception("Geçersiz kullanıcı bilgileri");

                            XDocument doc = XDocument.Load(file[0]);
                            XElement root = doc.Elements("_" + ImageProperty.GetUserName()).First();
                            XElement InstagramP = root.Elements("InstagramPhotos").FirstOrDefault();
                            XElement[] photos = (from p in InstagramP.Elements() where p.Attribute("useThis").Value.ToLower() == "true" select p).ToArray();
                            //list = new string[photos.Count()];

                            //for (int i = 0; i < photos.Count(); i++)
                            //    list[i] = Path.Combine(MiniPicturePath, photos[i].Value);

                            ///////////////////////////////////////////////////
                            if (photos.Count() == 0)
                                throw new Exception("Bu Formata Uygun Resimler Bulunamadı") { Source = "" };

                            List<ImgSquare> spl2 = new List<ImgSquare>();
                            for (int i = 0; i < photos.Count(); i++)
                            {
                                if (File.Exists(Path.Combine(MiniPicturePath, Path.GetFileName(photos[i].Value))))
                                {
                                    using (MagickImage mini = new MagickImage(Path.Combine(MiniPicturePath, Path.GetFileName(photos[i].Value))))
                                    {
                                        mini.Quality = 100;
                                        if (mini.Width != 94 && mini.Height != 94)
                                            mini.Resize((int)_pixFor, (int)_pixFor);

                                        //ImgSquare imgsq = new ImgSquare(mini.ToBitmap(), new List<QuardPixAvg>() { 
                                        //    new QuardPixAvg(Color.FromArgb(int.Parse(photos[i].Attribute("SolUst").Value)),QuardBolum.SagAlt),
                                        //    new QuardPixAvg(Color.FromArgb(int.Parse(photos[i].Attribute("SagUst").Value)),QuardBolum.SagAlt),
                                        //    new QuardPixAvg(Color.FromArgb(int.Parse(photos[i].Attribute("SolAlt").Value)),QuardBolum.SagAlt),
                                        //    new QuardPixAvg(Color.FromArgb(int.Parse(photos[i].Attribute("SagAlt").Value)),QuardBolum.SagAlt),
                                        //    new QuardPixAvg(Color.FromArgb(int.Parse(photos[i].Attribute("TotalAvg").Value)),QuardBolum.SagAlt)
                                        //});
                                        spl2.Add(new ImgSquare(mini.ToBitmap()));
                                        mini.Dispose();
                                    }
                                }
                            }
                            photos = null;
                            doc = null;
                            root = null;
                            InstagramP = null;
                            List<ImgSquare> spl4 = new List<ImgSquare>();
                            spl4.AddRange(sp0);
                            spl4.AddRange(spl2);
                            spl2.Clear();
                            spl4 = spl4.OrderBy(p => p.GeneratedColorCode).ToList();
                            int qpiro_number = 432101;
                            int qpiro_number2 = 0;
                            int undefined = 0;
                            for (int i = 0; i < sp0.Count; i++)
                            {
                                ImgSquare item = sp0[i];
                                //if (item.SAvgArb == 0 && item.IAvgRgb == 0)
                                //    continue;
                                try
                                {
                                    qpiro_number2 = 0;
                                    List<ImgSquare> snc = null;
                                    int cont = 0;
                                    do
                                    {
                                        snc = spl4.Where(p =>
                                            (p.GeneratedColorCode - (qpiro_number + qpiro_number2) < item.GeneratedColorCode &&
                                            p.GeneratedColorCode + (qpiro_number + qpiro_number2) > item.GeneratedColorCode) &&
                                            p.isArea == false).ToList();
                                        qpiro_number2 += 332101;
                                        cont++;
                                    }
                                    while (snc.Count == 0 && cont < 5);

                                    Rectangle rec = new Rectangle(item.W, item.H, (int)_pixFor, (int)_pixFor);

                                    if (snc.Count != 0)
                                    {
                                        int randi = random.Next(0, snc.Count);
                                        System.Drawing.Image img = SmartRotate(item, snc[randi]);
                                        snc.Clear();// 
                                        img = Transparnt(img, opacity);
                                        gr1.DrawImage(img, rec);
                                        sp0.RemoveAt(i);
                                        i--;
                                        img.Dispose();
                                    }
                                    else
                                    {
                                        using (MagickImage imgUndefined = new MagickImage(Path.Combine(UserProperty.Data_InstagramPhotos, "black.jpg")))
                                        {
                                            System.Drawing.Image img = Transparnt(imgUndefined.ToBitmap(), opacity);
                                            gr1.DrawImage(img, rec);
                                            sp0.RemoveAt(i);
                                            i--;
                                            imgUndefined.Dispose();
                                        }
                                        //int ss = item.GeneratedColorCode;
                                        //if (ss >= 11075440 && ss <= 15260100)
                                        //{
                                        //    cont = 0;
                                        // qpiro_number2 += 332101;
                                        //    do
                                        //    {
                                        //        snc = spl4.Where(p =>
                                        //            (p.GeneratedColorCode - (qpiro_number + qpiro_number2) < item.GeneratedColorCode &&
                                        //            p.GeneratedColorCode + (qpiro_number + qpiro_number2) > item.GeneratedColorCode) &&
                                        //            p.isArea == false).ToList();
                                        //        qpiro_number2 += 332101;
                                        //        cont++;
                                        //    }
                                        //    while (snc.Count == 0 && cont < 13);

                                        //    if (snc.Count != 0)
                                        //    {
                                        //        Rectangle rec = new Rectangle(item.W, item.H, (int)_pixFor, (int)_pixFor);
                                        //        int randi = random.Next(0, snc.Count);
                                        //        System.Drawing.Image img = SmartRotate(item, snc[randi]);
                                        //        snc.Clear();// 
                                        //        img = Transparnt(img, opacity);
                                        //        gr1.DrawImage(img, rec);
                                        //        sp0.RemoveAt(i);
                                        //        i--;
                                        //    }
                                        //    else
                                        //    {

                                        //    }
                                        //}
                                        undefined++;
                                    }
                                }
                                catch (Exception ef)
                                {
                                    throw ef;
                                }
                            }
                            sp0.Clear();
                            spl4.Clear();
                            gr1.Dispose();
                            //workingBitmap1.Save(Path.Combine(UsrImageProc.SavedPhotos_Path, Path.GetFileName(inputBitmapPath)));
                            //imglist.Add("lokale kaydettim");
                            Bitmap hd = btm.ArithmeticBlend(btm, ColorCalculationType.Add);
                            imglist.Add(ImageToBase64(hd, System.Drawing.Imaging.ImageFormat.Jpeg));
                            imglist.Add(ImageToBase64(btm, System.Drawing.Imaging.ImageFormat.Jpeg));
                            btm.Dispose();
                            hd.Dispose();
                            imagem.Dispose();
                        }
                    }
                    else
                    {
                        throw new Exception("Bu Formata Uygun Resimler Bulunamadı2") { Source = "" };
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return imglist;
        }
예제 #33
-1
 private void ExecuteResize(XmlElement element, MagickImage image)
 {
   Hashtable arguments = new Hashtable();
   foreach (XmlAttribute attribute in element.Attributes)
   {
     if (attribute.Name == "geometry")
       arguments["geometry"] = Variables.GetValue<MagickGeometry>(attribute);
     else if (attribute.Name == "height")
       arguments["height"] = Variables.GetValue<Int32>(attribute);
     else if (attribute.Name == "percentage")
       arguments["percentage"] = Variables.GetValue<Percentage>(attribute);
     else if (attribute.Name == "percentageHeight")
       arguments["percentageHeight"] = Variables.GetValue<Percentage>(attribute);
     else if (attribute.Name == "percentageWidth")
       arguments["percentageWidth"] = Variables.GetValue<Percentage>(attribute);
     else if (attribute.Name == "width")
       arguments["width"] = Variables.GetValue<Int32>(attribute);
   }
   if (OnlyContains(arguments, "geometry"))
     image.Resize((MagickGeometry)arguments["geometry"]);
   else if (OnlyContains(arguments, "percentage"))
     image.Resize((Percentage)arguments["percentage"]);
   else if (OnlyContains(arguments, "percentageWidth", "percentageHeight"))
     image.Resize((Percentage)arguments["percentageWidth"], (Percentage)arguments["percentageHeight"]);
   else if (OnlyContains(arguments, "width", "height"))
     image.Resize((Int32)arguments["width"], (Int32)arguments["height"]);
   else
     throw new ArgumentException("Invalid argument combination for 'resize', allowed combinations are: [geometry] [percentage] [percentageWidth, percentageHeight] [width, height]");
 }
예제 #34
-1
    public void Test_Resize()
    {
      using (MagickImage image = new MagickImage())
      {
        image.Read(Files.MagickNETIconPNG);
        image.Resize(new MagickGeometry(64, 64));
        Assert.AreEqual(64, image.Width);
        Assert.AreEqual(64, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize((Percentage)200);
        Assert.AreEqual(256, image.Width);
        Assert.AreEqual(256, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize(32, 32);
        Assert.AreEqual(32, image.Width);
        Assert.AreEqual(32, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize(new MagickGeometry("5x10!"));
        Assert.AreEqual(5, image.Width);
        Assert.AreEqual(10, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize(new MagickGeometry("32x32<"));
        Assert.AreEqual(128, image.Width);
        Assert.AreEqual(128, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize(new MagickGeometry("256x256<"));
        Assert.AreEqual(256, image.Width);
        Assert.AreEqual(256, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize(new MagickGeometry("32x32>"));
        Assert.AreEqual(32, image.Width);
        Assert.AreEqual(32, image.Height);

        image.Read(Files.MagickNETIconPNG);
        image.Resize(new MagickGeometry("256x256>"));
        Assert.AreEqual(128, image.Width);
        Assert.AreEqual(128, image.Height);

        image.Read(Files.SnakewarePNG);
        image.Resize(new MagickGeometry("4096@"));
        Assert.IsTrue((image.Width * image.Height) < 4096);

        Percentage percentage = new Percentage(-0.5);
        ExceptionAssert.Throws<ArgumentException>(delegate ()
        {
          image.Resize(percentage);
        });
      }
    }
예제 #35
-1
        public bool Save()
        {
            try
            {
                Database db = new Database("Database");

                string destPath = Path.Combine(ConfigurationManager.AppSettings["destinationFolder"], this.FilePath, this.FileName);
                if (!Directory.Exists(Path.GetDirectoryName(destPath))) Directory.CreateDirectory(Path.GetDirectoryName(destPath));
                // If this throws an error the archive code is not working
                fileInfo.MoveTo(destPath);
                // Read from file
                using (MagickImage image = new MagickImage(destPath))
                {
                    MagickGeometry size = new MagickGeometry(200, 200);
                    size.IgnoreAspectRatio = true;
                    image.Resize(size);
                    image.Write(destPath + "_small");
                }

                using (MagickImage image = new MagickImage(destPath))
                {
                    MagickGeometry size = new MagickGeometry(800, 800);
                    size.IgnoreAspectRatio = true;
                    image.Resize(size);
                    image.Write(destPath + "_medium");
                }

                FTP.UploadFile(this);
                db.Insert(this);

                return true;
            }
            catch (Exception ex)
            {
                Logger.WriteLine("Could not insert {0} into the database: {1}", this.Name, ex);
                return false;
            }
        }
예제 #36
-20
        public string ExecuteThread(FileItem item, string infile, string dest, ValuePairEnumerator configData)
        {
            var conf = new OverlayTransformViewModel(configData);
            using (MagickImage image = new MagickImage(infile))
            {
                Gravity gravity = Gravity.Center;
                if (conf.A11)
                {
                    gravity = Gravity.Northwest;
                }
                if (conf.A12)
                {
                    gravity = Gravity.North;
                }
                if (conf.A13)
                {
                    gravity = Gravity.Northeast;
                }
                if (conf.A21)
                {
                    gravity = Gravity.West;
                }
                if (conf.A22)
                {
                    gravity = Gravity.Center;
                }
                if (conf.A23)
                {
                    gravity = Gravity.East;
                }
                if (conf.A31)
                {
                    gravity = Gravity.Southwest;
                }
                if (conf.A32)
                {
                    gravity = Gravity.South;
                }
                if (conf.A33)
                {
                    gravity = Gravity.Southeast;
                }


                if (File.Exists(conf.OverlayFile))
                {
                    // Read the watermark that will be put on top of the image
                    using (MagickImage watermark = new MagickImage(conf.OverlayFile))
                    {
                        if (conf.StrechOverlay)
                            watermark.Resize(image.Width, image.Height);
                        // Optionally make the watermark more transparent
                        if (conf.Transparency != 100)
                            watermark.Evaluate(Channels.Alpha, EvaluateOperator.Add,
                                -(255*(100 - conf.Transparency)/100));
                        // Draw the watermark in the bottom right corner
                        image.Composite(watermark, gravity, CompositeOperator.Over);

                        //// Optionally make the watermark more transparent
                        //watermark.Evaluate(Channels.Alpha, EvaluateOperator.Divide, 4);

                        //// Or draw the watermark at a specific location
                        //image.Composite(watermark, 200, 50, CompositeOperator.Over);
                    }
                }

                string text = "";
                if (!string.IsNullOrEmpty(conf.Text))
                {
                    Regex regPattern = new Regex(@"\[(.*?)\]", RegexOptions.Singleline);
                    MatchCollection matchX = regPattern.Matches(conf.Text);
                    text = matchX.Cast<Match>()
                        .Aggregate(conf.Text,
                            (current1, match) =>
                                item.FileNameTemplates.Where(
                                    template =>
                                        String.Compare(template.Name, match.Value,
                                            StringComparison.InvariantCultureIgnoreCase) == 0).Aggregate(current1,
                                                (current, template) => current.Replace(match.Value, template.Value)));

                    image.Font = conf.Font;
                    image.FontPointsize = conf.FontSize;
                    Color color = (Color) ColorConverter.ConvertFromString(conf.FontColor);
                    image.FillColor = new MagickColor(color.R, color.G, color.B, color.A);
                    image.StrokeColor = new MagickColor(color.R, color.G, color.B, color.A);
                    image.Annotate(text, gravity);
                }
                image.Format = MagickFormat.Jpeg;
                image.Write(dest);
            }
            return dest;
        }