コード例 #1
10
ファイル: Chromakey.cs プロジェクト: CadeLaRen/digiCamControl
        public string Execute(FileItem item, string infile, string dest, ValuePairEnumerator configData)
        {
            var conf = new ChromakeyViewModel(configData);
            dest = Path.Combine(Path.GetDirectoryName(dest), Path.GetFileNameWithoutExtension(dest) + ".jpg");

            KalikoImage image = new KalikoImage(infile);
            var x = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(conf.BackgroundColor);
            var filter = new ChromaKeyFilter();
            filter.KeyColor = Color.FromArgb(x.R, x.G, x.B);
            filter.ToleranceHue = conf.Hue;
            filter.ToleranceSaturnation = conf.Saturnation/100f;
            filter.ToleranceBrightness = conf.Brigthness / 100f;
            image.ApplyFilter(filter);
            var res = image.Clone();
            
            if (conf.UnsharpMask)
                res.ApplyFilter(new UnsharpMaskFilter(1.4f, 1.32f, 5));

            var backdrop = new KalikoImage(conf.BackgroundFile);
            backdrop = backdrop.Scale(new FitScaling(image.Width, image.Height));
            backdrop.BlitImage(res);

            backdrop.SaveJpg(dest, 90);
            return dest;
        }
コード例 #2
0
        private void CreateThumb(string path, string localThumbPath) {
            EnsureThumbnailPath();

            var image = new KalikoImage(path);
            var thumbnail = image.Scale(new CropScaling(128,128));
            thumbnail.SaveJpg(localThumbPath, 85);
        }
コード例 #3
0
ファイル: ThumbGenerator.cs プロジェクト: CuteThalia/voat
        // store uploaded avatar
        public static async Task<bool> GenerateAvatar(Image inputImage, string userName, string mimetype)
        {
            try
            {
                // store avatar locally
                var originalImage = new KalikoImage(inputImage);
                originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPathAvatars + '\\' + userName + ".jpg", 90);
                if (!Settings.UseContentDeliveryNetwork) return true;

                // call upload to storage since CDN is enabled in config
                string tempAvatarLocation = DestinationPathAvatars + '\\' + userName + ".jpg";

                // the avatar file was not found at expected path, abort
                if (!FileSystemUtility.FileExists(tempAvatarLocation, DestinationPathAvatars)) return false;

                // upload to CDN
                await CloudStorageUtility.UploadBlobToStorageAsync(tempAvatarLocation, "avatars");

                // delete local file after uploading to CDN
                File.Delete(tempAvatarLocation);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
コード例 #4
0
        /// <summary>Resizes the image without any <span lang="en" id="result_box" class="short_text" xml:lang="en"><span class="hps alt-edited">consideration of the current
        /// ratio. If you wish to make a ratio locked resize use <see cref="Scale">Scale Method</see> instead.</span></span></summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <seealso cref="M:Kaliko.ImageLibrary.KalikoImage.Scale(Kaliko.ImageLibrary.Scaling.ScalingBase)"></seealso>
        public void Resize(int width, int height)
        {
            int newWidth  = width;
            int newHeight = height;

            if (newWidth == 0 && newHeight == 0)
            {
                return;
            }

            if (newWidth == 0)
            {
                newWidth = Image.Width * newHeight / Image.Height;
            }
            else if (newHeight == 0)
            {
                newHeight = Image.Height * newWidth / Image.Width;
            }

            var image = new KalikoImage(newWidth, newHeight);

            DrawScaledImage(image.Image, Image, 0, 0, newWidth, newHeight);

            Image = image.Image;
        }
コード例 #5
0
        public void Draw(KalikoImage image)
        {
            var graphics     = image.Graphics;
            var graphicsPath = new GraphicsPath();
            var stringFormat = new StringFormat {
                Alignment     = Alignment,
                LineAlignment = VerticalAlignment
            };

            graphics.SmoothingMode   = SmoothingMode.AntiAlias;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            if (Font == null)
            {
                Font = image.Font ?? new Font("Arial", 32, FontStyle.Bold, GraphicsUnit.Pixel);
            }

            if (TargetArea == Rectangle.Empty)
            {
                TargetArea = new Rectangle(0, 0, image.Width, image.Height);
            }

            if (Point == Point.Empty)
            {
                graphicsPath.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, TargetArea, stringFormat);
            }
            else
            {
                graphicsPath.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, Point, stringFormat);
            }

            if (Rotation != 0)
            {
                var rotationTransform = new Matrix(1, 0, 0, 1, 0, 0);
                var bounds            = graphicsPath.GetBounds();
                rotationTransform.RotateAt(Rotation, new PointF(bounds.X + (bounds.Width / 2f), bounds.Y + (bounds.Height / 2f)));
                graphicsPath.Transform(rotationTransform);
            }

            if (TextShadow != null)
            {
                DrawShadow(graphics, graphicsPath);
            }

            if (Outline > 0)
            {
                var pen = new Pen(OutlineColor, Outline)
                {
                    LineJoin = LineJoin.Round
                };
                graphics.DrawPath(pen, graphicsPath);
            }

            if (TextBrush == null)
            {
                TextBrush = new SolidBrush(TextColor);
            }

            graphics.FillPath(TextBrush, graphicsPath);
        }
コード例 #6
0
ファイル: ThumbGenerator.cs プロジェクト: rnand/voat
        // store uploaded avatar
        public static async Task<bool> GenerateAvatar(Image inputImage, string userName, string mimetype)
        {
            try
            {
                // call upload to storage if CDN config is enabled
                if (Settings.UseContentDeliveryNetwork)
                {
                    string tempAvatarLocation = DestinationPathAvatars + '\\' + userName + ".jpg";
                    if (FileExists(tempAvatarLocation, DestinationPathAvatars))
                    {
                        await UploadBlobToStorageAsync(tempAvatarLocation, "avatars");

                        // delete local file after uploading to CDN
                        File.Delete(tempAvatarLocation);
                    }
                    return true;
                }
                
                // store avatar locally
                var originalImage = new KalikoImage(inputImage);
                originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPathAvatars + '\\' + userName + ".jpg", 90);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
コード例 #7
0
ファイル: ThumbGenerator.cs プロジェクト: dkempner/voat
        // generate a thumbnail while removing transparency and preserving aspect ratio
        public static async Task<string> GenerateThumbFromUrl(string sourceUrl)
        {
            var randomFileName = GenerateRandomFilename();

            var request = WebRequest.Create(sourceUrl);
            request.Timeout = 300;
            var response = request.GetResponse();

            var originalImage = new KalikoImage(response.GetResponseStream()) { BackgroundColor = Color.Black };
            
            originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPath + '\\' + randomFileName + ".jpg", 90);
            
            // call upload to storage method if CDN config is enabled
            if (MvcApplication.UseContentDeliveryNetwork)
            {
                string tempThumbLocation = DestinationPath + '\\' + randomFileName + ".jpg";

                if (FileExists(tempThumbLocation))
                {
                    await UploadBlobToStorageAsync(tempThumbLocation);

                    // delete local file after uploading to CDN
                    File.Delete(tempThumbLocation);
                }
            }

            return randomFileName + ".jpg";
        }
コード例 #8
0
        /// <summary>Crop the image into the given dimensions.</summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public void Crop(int x, int y, int width, int height)
        {
            var image = new KalikoImage(width, height);

            image.BlitImage(Image, -x, -y);

            Image = image.Image;
        }
コード例 #9
0
ファイル: KalikoImage.cs プロジェクト: rensy/NetImageLibrary
        /// <summary>
        /// Create a new image as a clone.
        /// </summary>
        /// <returns></returns>
        public KalikoImage Clone()
        {
            var newImage = new KalikoImage(Image)
            {
                Color             = Color,
                _font             = _font,
                BackgroundColor   = BackgroundColor,
                TextRenderingHint = TextRenderingHint
            };

            return(newImage);
        }
コード例 #10
0
ファイル: ThumbGenerator.cs プロジェクト: blakar/voat
        // generate a thumbnail while removing transparency and preserving aspect ratio
        public static string GenerateThumbFromUrl(string sourceUrl)
        {
            var randomFileName = GenerateRandomFilename();

            var request = WebRequest.Create(sourceUrl);
            request.Timeout = 300;
            var response = request.GetResponse();

            var originalImage = new KalikoImage(response.GetResponseStream()) { BackgroundColor = Color.Black };
            originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPath + '\\' + randomFileName + ".jpg", 90);

            return randomFileName + ".jpg";
        }
コード例 #11
0
        public static void SetPixel(this KalikoImage ki, int x, int y, byte r, byte g, byte b, byte a)
        {
            byte[] byteArray = ki.ByteArray;

            int offset = (x + y * ki.Width) * 4;

            byteArray[offset]     = b;
            byteArray[offset + 1] = g;
            byteArray[offset + 2] = r;
            byteArray[offset + 3] = a;

            ki.ByteArray = byteArray;       // assignment creates proper bitmaps & handles other operations
        }
コード例 #12
0
 private static BitmapImage KalikoToBitmap(KalikoImage kimage)
 {
     var stream = new MemoryStream();
     kimage.SavePng(stream);
     stream.Position = 0;
     var bitmap = new BitmapImage();
     bitmap.BeginInit();
     bitmap.CacheOption = BitmapCacheOption.OnLoad;
     bitmap.StreamSource = stream;
     bitmap.EndInit();
     bitmap.Freeze();
     return bitmap;
 }
コード例 #13
0
ファイル: TextField.cs プロジェクト: dwinkelman/imagelibrary
        public void Draw(KalikoImage image) {
            var graphics = image.Graphics;
            var graphicsPath = new GraphicsPath();
            var stringFormat = new StringFormat {
                Alignment = Alignment,
                LineAlignment = VerticalAlignment
            };

            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            if (Font == null) {
                Font = image.Font ?? new Font("Arial", 32, FontStyle.Bold, GraphicsUnit.Pixel);
            }

            if (TargetArea == Rectangle.Empty) {
                TargetArea = new Rectangle(0, 0, image.Width, image.Height);
            }

            if (Point == Point.Empty) {
                graphicsPath.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, TargetArea, stringFormat);
            }
            else {
                graphicsPath.AddString(Text, Font.FontFamily, (int)Font.Style, Font.Size, Point, stringFormat);
            }

            if (Rotation != 0) {
                var rotationTransform = new Matrix(1, 0, 0, 1, 0, 0);
                var bounds = graphicsPath.GetBounds();
                rotationTransform.RotateAt(Rotation, new PointF(bounds.X + (bounds.Width / 2f), bounds.Y + (bounds.Height / 2f)));
                graphicsPath.Transform(rotationTransform);
            }

            if (TextShadow != null) {
                DrawShadow(graphics, graphicsPath);
            }

            if (Outline > 0) {
                var pen = new Pen(OutlineColor, Outline) {
                    LineJoin = LineJoin.Round
                };
                graphics.DrawPath(pen, graphicsPath);
            }

            if (TextBrush == null) {
                TextBrush = new SolidBrush(TextColor);
            }

            graphics.FillPath(TextBrush, graphicsPath);
        }
コード例 #14
0
        /// <summary>
        /// Create a new image as a clone.
        /// </summary>
        /// <returns></returns>
        public KalikoImage Clone()
        {
            var newImage = new KalikoImage(Image)
            {
                Color                = Color,
                _font                = _font,
                BackgroundColor      = BackgroundColor,
                TextRenderingHint    = TextRenderingHint,
                HorizontalResolution = HorizontalResolution,
                VerticalResolution   = VerticalResolution
            };

            return(newImage);
        }
コード例 #15
0
 internal static void SaveFile(KalikoImage image, string fileName, ImageFormat imageFormat, bool saveResolution)
 {
     if (saveResolution)
     {
         using (var copy = new Bitmap(image.Image)) {
             copy.SetResolution(image.HorizontalResolution, image.VerticalResolution);
             copy.Save(fileName, imageFormat);
         }
     }
     else
     {
         image.Image.Save(fileName, imageFormat);
     }
 }
コード例 #16
0
 internal static void SaveStream(KalikoImage image, Stream stream, ImageFormat imageFormat, bool saveResolution)
 {
     if (saveResolution)
     {
         using (var copy = new Bitmap(image.Image)) {
             copy.SetResolution(image.HorizontalResolution, image.VerticalResolution);
             copy.Save(stream, imageFormat);
         }
     }
     else
     {
         image.Image.Save(stream, imageFormat);
     }
 }
コード例 #17
0
 private async Task ConvertBackgroundBlurAsync(bool overwrite)
 {
     await Task.Run(() =>
     {
         filesToZip.Add(LimProjectManager.LapFolder + "/Layesta/background_blur.png");
         if (File.Exists(LimProjectManager.LapFolder + "/Layesta/background_blur.png") && !overwrite)
         {
             return;
         }
         Kaliko.ImageLibrary.KalikoImage k = new Kaliko.ImageLibrary.KalikoImage(LimProjectManager.LapFolder + "/Layesta/background.jpg");
         k = k.Scale(new Kaliko.ImageLibrary.Scaling.PadScaling((int)(64f / k.Height *k.Width), 64));
         k.ApplyFilter(new Kaliko.ImageLibrary.Filters.GaussianBlurFilter(5));
         k.SavePng(LimProjectManager.LapFolder + "/Layesta/background_blur.png");
     });
 }
コード例 #18
0
        internal static void SaveFile(KalikoImage image, string fileName, long quality, string imageFormat, bool saveResolution)
        {
            var encoderParameters = GetEncoderParameters(quality);
            var encoderInfo       = GetEncoderInfo(imageFormat);

            if (saveResolution)
            {
                using (var copy = new Bitmap(image.Image)) {
                    copy.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                    copy.Save(fileName, encoderInfo, encoderParameters);
                }
            }
            else
            {
                image.Image.Save(fileName, encoderInfo, encoderParameters);
            }
        }
コード例 #19
0
ファイル: ThumbGenerator.cs プロジェクト: dkempner/voat
        // TODO: implement CDN routing for avatars
        public static bool GenerateAvatar(Image inputImage, string userName, string mimetype)
        {
            try
            {
                string DestinationPath = HttpContext.Current.Server.MapPath("~/Storage/Avatars");

                var originalImage = new KalikoImage(inputImage);

                originalImage.Scale(new PadScaling(MaxWidth, MaxHeight)).SaveJpg(DestinationPath + '\\' + userName + ".jpg", 90);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
コード例 #20
0
        public static void DrawMarker(this KalikoImage ki, Point p, Color col, int radius = 1)
        {
            List <Point> points = new List <Point>();

            for (int j = -radius; j < radius; ++j)
            {
                for (int i = -radius; i < radius; ++i)
                {
                    int x = p.X + i;
                    int y = p.Y + j;
                    if (ki.IsPointCorrect(x, y))
                    {
                        points.Add(new Point(x, y));
                    }
                }
            }

            SetPixels(ki, points, col);
        }
コード例 #21
0
        public static void SetPixels(this KalikoImage ki, List <Point> points, Color col)
        {
            byte[] byteArray = ki.ByteArray;

            for (int i = 0; i < points.Count; ++i)
            {
                Point p = points[i];
                if (p != null)
                {
                    int offset = (p.X + p.Y * ki.Width) * 4;

                    byteArray[offset]     = col.B;
                    byteArray[offset + 1] = col.G;
                    byteArray[offset + 2] = col.R;
                    byteArray[offset + 3] = col.A;
                }
            }

            ki.ByteArray = byteArray;
        }
コード例 #22
0
    public async void GenerateMultiple()
    {
        string projectName   = LimProjectManager.CurrentProject.Name;
        string projectAuthor = LimProjectManager.CurrentProject.Designer;
        string projectArtist = "Yooh";
        string outputPath    = $"E:/LanotaNS/{projectName}.layesta";
        string originFolder  = @"E:\ns\ThefuckingswitchLanota\marianne";

        Directory.CreateDirectory(LimProjectManager.LapFolder + "/Layesta");
        filesToZip.Clear();
        EncodeBackgrounds(true);
        await ConvertAudioAsync(true);
        await ConvertBackgroundBlurAsync(true);

        filesToZip.Add(originFolder + @"\chart_Acoustic.txt");
        filesToZip.Add(originFolder + @"\chart_Whisper.txt");
        filesToZip.Add(originFolder + @"\chart_Ultra.txt");
        filesToZip.Add(originFolder + @"\chart_Master.txt");
        await Task.Run(() =>
        {
            FileStream fs  = new FileStream(LimProjectManager.LapFolder + "/Layesta/info.bytes", FileMode.Create, FileAccess.Write);
            BinaryWriter b = new BinaryWriter(fs);
            b.Write(projectName);
            b.Write(projectAuthor);
            b.Write(4);
            b.Write("Whisper");
            b.Write("Acoustic");
            b.Write("Ultra");
            b.Write("Master");
            Kaliko.ImageLibrary.KalikoImage k = new Kaliko.ImageLibrary.KalikoImage(LimProjectManager.LapFolder + "/Layesta/background.jpg");
            b.Write(k.Width);
            b.Write(k.Height);
            b.Write(projectArtist);
            b.Close();
            fs.Close();
            filesToZip.Add(LimProjectManager.LapFolder + "/Layesta/info.bytes");
            lzip.compress_File_List(0, LimProjectManager.LapFolder + "/instance.layesta", filesToZip.ToArray(), null, false, filesToZip.Select((s) => Path.GetFileName(s)).ToArray());
        });

        File.Move(LimProjectManager.LapFolder + "/instance.layesta", outputPath);
    }
コード例 #23
0
ファイル: Program.cs プロジェクト: dwinkelman/imagelibrary
        static void Main(string[] args) {
            KalikoImage image = new KalikoImage("testimage.jpg");
            image.BackgroundColor = Color.Aquamarine;

            image.Scale(new FitScaling(100, 100)).SaveJpg("thumbnail-fit.jpg", 90);

            image.Scale(new CropScaling(100,100)).SaveJpg("thumbnail-crop.jpg", 90);

            image.Scale(new PadScaling(100, 100)).SaveJpg("thumbnail-pad.jpg", 90);

            KalikoImage sharpimg = image.Scale(new CropScaling(100, 100));
            sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2f, 0.3f, 1));
            sharpimg.SaveJpg("thumbnail-unsharpened.jpg", 90);

            sharpimg.ApplyFilter(new DesaturationFilter());
            sharpimg.SaveJpg("thumbnail-gray.jpg", 90);

            sharpimg.ApplyFilter(new ContrastFilter(30));
            sharpimg.SaveJpg("thumbnail-contrast.jpg", 90);

        }
コード例 #24
0
 private async Task PackLayestaFileInstanceAsync()
 {
     await Task.Run(() =>
     {
         FileStream fs  = new FileStream(LimProjectManager.LapFolder + "/Layesta/info.bytes", FileMode.Create, FileAccess.Write);
         BinaryWriter b = new BinaryWriter(fs);
         b.Write(Name.text);
         b.Write(Designer.text);
         b.Write(1);
         b.Write("Master");
         Kaliko.ImageLibrary.KalikoImage k = new Kaliko.ImageLibrary.KalikoImage(LimProjectManager.LapFolder + "/Layesta/background.jpg");
         b.Write(k.Width);
         b.Write(k.Height);
         b.Write(Artist.text);
         b.Write(2);
         b.Close();
         fs.Close();
         filesToZip.Add(LimProjectManager.LapFolder + "/Layesta/info.bytes");
         lzip.compress_File_List(0, LimProjectManager.LapFolder + "/instance.layesta", filesToZip.ToArray(), null, false, filesToZip.Select((s) => Path.GetFileName(s)).ToArray());
     });
 }
コード例 #25
0
        private string SaveImage() {
            if (!DoesImageNeedHandling) {
                return _originalPath;
            }

            var image = new KalikoImage(Server.MapPath(_originalPath));

            // TODO: Temporary fix for selecting full image, try to do this without loading the image first..
            if (IsCropValueFullImage(image)) {
                return _originalPath;
            }

            if (_hasCropValues) {
                image.Crop(_cropX, _cropY, _cropW, _cropH);
            }

            if (_width > 0 || _height > 0) {
                image.Resize(_width, _height);
            }

            var imagePath = GetNewImagePath();
            var serverPath = Server.MapPath(imagePath);

            if (File.Exists(serverPath)) {
                var originalServerPath = Server.MapPath(_originalPath);

                if (File.GetLastWriteTime(originalServerPath) < File.GetLastWriteTime(serverPath)) {
                    return imagePath;
                }

                File.Delete(serverPath);
            }

            // TODO: Config quality
            image.SaveJpg(Server.MapPath(imagePath), 90);

            return imagePath;
        }
コード例 #26
0
ファイル: Histogram.cs プロジェクト: Spierek/biomet-handscan
 public Histogram(KalikoImage image)
 {
     Calculate(image.ByteArray);
 }
コード例 #27
0
ファイル: ImageManager.cs プロジェクト: beachead/gooey-cms-v2
        private void GenerateThumbnail(StorageFile file, IList<StorageFile> results)
        {
            if (file.Data.Length > 0)
            {
                using (MemoryStream stream = new MemoryStream(file.Data))
                {
                    using (MemoryStream output = new MemoryStream())
                    {
                        try
                        {
                            KalikoImage image = new KalikoImage(stream);
                            int width = 60;
                            int height = 60;

                            image.BackgroundColor = Color.White;
                            KalikoImage thumb = image.GetThumbnailImage(width, height, ThumbnailMethod.Pad);
                            thumb.SaveJpg(output, 75);

                            FileInfo info = new FileInfo(file.Filename);

                            StorageFile thumbnail = new StorageFile();
                            thumbnail.Filename = info.Name.Replace(info.Extension, "") + "-thumb.jpg";
                            thumbnail.Data = output.ToArray();

                            results.Add(thumbnail);
                        }
                        catch (Exception)
                        {
                            throw new ArgumentException("The uploaded content is not supported. Must be a valid image type (png,jpeg or gif)");
                        }
                    }
                }
            }
        }
コード例 #28
0
 public static void SetPixel(this KalikoImage ki, int x, int y, Color col)
 {
     SetPixel(ki, x, y, col.R, col.G, col.B, col.A);
 }
コード例 #29
0
 /// <summary>Will take the source image and place it on the destination image at the defined coordinates.</summary>
 /// <param name="image"></param>
 /// <param name="x"></param>
 /// <param name="y"></param>
 /// <example>
 /// 	<code title="Example" description="" lang="CS">
 /// // Place the source image 10 pixels from the left and 20 pixels from the top
 /// var sourceImage = new KalikoImage(@"C:\Img\Stamp.png");
 /// image.BlitImage(sourceImage, 10, 20);</code>
 /// </example>
 public void BlitImage(KalikoImage image, int x, int y) {
     BlitImage(image.Image, x, y);
 }
コード例 #30
0
 /// <summary>Will take the source image and place it on the destination image at top left corner.</summary>
 /// <param name="image"></param>
 /// <example>
 ///     <code title="Example" description="" lang="CS">
 /// // Place the source image on top, left of our image
 /// var sourceImage = new KalikoImage(@"C:\Img\Stamp.png");
 /// image.BlitImage(sourceImage);</code>
 /// </example>
 public void BlitImage(KalikoImage image)
 {
     BlitImage(image.Image, 0, 0);
 }
コード例 #31
0
ファイル: BannerController.cs プロジェクト: ecolinx/cms
        public Task<string> Upload(int id)
        {
            try
            {
                //cria a parta obra
                if (Request.Content.IsMimeMultipartContent())
                {
                    var pathImagem = HttpContext.Current.Server.MapPath("~/Content/images/site/banner");
                    var pathThumb = HttpContext.Current.Server.MapPath("~/Content/images/site/banner/thumbs");
                    var streamProvider = new GuidMultipartFormDataStreamProvider(pathImagem);

                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<string>(t =>
                    {
                        var fileName = "";

                        //verifica se tem imagem
                        if (streamProvider.FileData.Count > 0)
                        {
                            //altera o nome da imagem
                            fileName = streamProvider.GetLocalFileName(streamProvider.FileData[0].Headers);

                            //cria o thumb
                            var combine = Path.Combine(pathImagem, fileName);
                            KalikoImage image = new KalikoImage(combine);
                            KalikoImage thumb = image.Scale(new CropScaling(150, 150));

                            image.BackgroundColor = Color.White;
                            thumb.SaveJpg(Path.Combine(pathThumb, fileName), 99);

                            //dispose das imagens
                            thumb.Dispose();
                            image.Dispose();

                            //verifica se é para atualizar a logomarca
                            if (id > 0)
                            {
                                var banner = _service.Banner.Get(id);
                                banner.Imagem = fileName;
                                banner.Thumbnail = fileName;
                                _service.Banner.Update(banner);
                            }
                        }

                        return fileName;
                    });

                    return task;
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
                }
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, ex.Message));
            }
        }
コード例 #32
0
 internal static void DrawScaledImage(
     KalikoImage destinationImage, KalikoImage sourceImage, int x, int y, int width, int height) {
     DrawScaledImage(destinationImage.Image, sourceImage.Image, x, y, width, height);
 }
コード例 #33
0
 public static bool IsPointCorrect(this KalikoImage ki, int x, int y)
 {
     return(x >= 0 && y >= 0 && x < ki.Width - 1 && y < ki.Height - 1);
 }
コード例 #34
0
        /// <summary>Crop the image into the given dimensions.</summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public void Crop(int x, int y, int width, int height) {
            var image = new KalikoImage(width, height);
            image.BlitImage(Image, -x, -y);

            Image = image.Image;
        }
コード例 #35
0
ファイル: PortifolioController.cs プロジェクト: ecolinx/cms
        public Task<FroalaUploadHelper> Upload()
        {
            try
            {
                //cria a parta obra
                if (Request.Content.IsMimeMultipartContent())
                {
                    var pathImagem = HttpContext.Current.Server.MapPath("~/Content/images/site/portifolio");
                    var pathThumb = HttpContext.Current.Server.MapPath("~/Content/images/site/portifolio/thumbs");
                    var imagePath = @"../Content/images/site/portifolio";
                    var streamProvider = new CustomMultipartFormDataStreamProvider(pathImagem);

                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<FroalaUploadHelper>(t =>
                    {
                        var fileName = "";

                        //verifica se tem imagem
                        if (streamProvider.FileData.Count > 0)
                        {
                            //altera o nome da imagem
                            fileName = streamProvider.GetLocalFileName(streamProvider.FileData[0].Headers);

                            //cria o thumb
                            var combine = Path.Combine(pathImagem, fileName);
                            KalikoImage image = new KalikoImage(combine);
                            KalikoImage thumb = image.Scale(new CropScaling(150, 150));

                            image.BackgroundColor = Color.White;
                            thumb.SaveJpg(Path.Combine(pathThumb, fileName), 99);

                            //dispose das imagens
                            thumb.Dispose();
                            image.Dispose();
                        }

                        return new FroalaUploadHelper
                        {
                            link = imagePath + "/" + fileName
                        };
                    });

                    return task;
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
                }
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, ex.Message));
            }
        }
コード例 #36
0
 /// <summary>Uses the defined image as a pattern to fill the image (will be tiled if the destination image is larger than the source image)..</summary>
 /// <param name="image"></param>
 /// <example>
 ///     <code title="Example" description="" lang="CS">
 /// // Create a new image and fill the source image all over
 /// var image = new KalikoImage(640, 480);
 /// var patternImage = new KalikoImage(@"C:\Img\Checkered.png");
 /// image.BlitFill(patternImage);</code>
 /// </example>
 public void BlitFill(KalikoImage image)
 {
     BlitFill(image.Image);
 }
コード例 #37
0
 /// <summary>Will take the source image and place it on the destination image at the defined coordinates.</summary>
 /// <param name="image"></param>
 /// <param name="x"></param>
 /// <param name="y"></param>
 /// <example>
 ///     <code title="Example" description="" lang="CS">
 /// // Place the source image 10 pixels from the left and 20 pixels from the top
 /// var sourceImage = new KalikoImage(@"C:\Img\Stamp.png");
 /// image.BlitImage(sourceImage, 10, 20);</code>
 /// </example>
 public void BlitImage(KalikoImage image, int x, int y)
 {
     BlitImage(image.Image, x, y);
 }
コード例 #38
0
        private String ConvertUploadedImageToPng(string fullImagePath, string pngFileName)
        {
            var origImg = new KalikoImage(fullImagePath);
            var pathWOFileName = fullImagePath.Replace(Path.GetFileName(fullImagePath), "");
            var newPngPath = String.Format(@"{0}{1}", pathWOFileName, pngFileName);
            origImg.SavePNG(newPngPath, 95L);
            //If successful, delete original image
            try
            {
                GC.Collect();
                System.IO.File.Delete(fullImagePath);
            }
            catch (Exception e)
            {
                //Log Problem
            }

            return newPngPath;
        }
コード例 #39
0
ファイル: ImageHandler.cs プロジェクト: cataylor/bananasplit
        public static ImagePaths SaveThumbnail(string originalImagePath, int thumbSize = DEFAULT_THUMB_SIZE, int imgQuality = 95)
        {
            var origImg = new KalikoImage(originalImagePath);

            //Create thumbnail name from original image name
            //var ext = Path.GetExtension(originalImagePath);
            //var imgWOExt = Path.GetFileNameWithoutExtension(originalImagePath);
            var newThumbName = GetUniqueFileName(originalImagePath, "thumb");// String.Format("{0}_thumb.{1}", imgWOExt, ext);

            //var origFileName = Path.GetFileName(originalImagePath);

            var newThumbPath = GetNewFullPath(originalImagePath, newThumbName); // originalImagePath.Replace(origFileName, newThumbName);

            var splitPath = originalImagePath.Split(@"\".ToCharArray());
            var unixStyleFolderPortion = new StringBuilder();
            for (var i = 0; i < splitPath.Length; i++)
            {
                if (i == 0) { continue; } //We don't want the drive letter
                if (i == splitPath.Length - 1) { break; } //we don't want the fileName either
                unixStyleFolderPortion.AppendFormat("{0}/", splitPath[i]);  //we just need the folder paths
            }

            var dateFolder = splitPath[splitPath.Length - 2];

            origImg.GetThumbnailImage(thumbSize, thumbSize, ThumbnailMethod.Crop).SavePNG(newThumbPath, imgQuality);
            //var webAddress = String.Concat(ConfigurationManager.AppSettings["BaseDomain"], unixStyleFolderPortion.ToString(), newThumbName);
            //var webAddress = String.Concat(ConfigurationManager.AppSettings["BaseDomain"], "Uploads/", dateFolder, slash, newThumbName);
            var webAddress = String.Concat(ConfigurationManager.AppSettings["BaseDomain"], "Uploads/", newThumbName);
            //var sqlAddress = String.Format("{0}{1}", unixStyleFolderPortion.ToString(), newThumbName);
            //var sqlAddress = String.Format("Uploads/{0}{1}{2}", dateFolder, slash, newThumbName);
            var sqlAddress = String.Format("Uploads/{0}", newThumbName);

            var paths = new ImagePaths(webAddress, sqlAddress, newThumbPath);

            return paths;
        }
コード例 #40
0
        /// <summary>
        /// Create a new image as a clone.
        /// </summary>
        /// <returns></returns>
        public KalikoImage Clone() {
            var newImage = new KalikoImage(Image) {
                Color = Color, 
                _font = _font, 
                BackgroundColor = BackgroundColor, 
                TextRenderingHint = TextRenderingHint
            };

            return newImage;
        }
コード例 #41
0
ファイル: ImagemController.cs プロジェクト: ecolinx/cms
        public Task<Imagem> UploadInsert(int id)
        {
            try
            {
                //cria a parta obra
                if (Request.Content.IsMimeMultipartContent())
                {
                    var pathImagem = HttpContext.Current.Server.MapPath("~/Content/images/site/galeria");
                    var pathThumb = HttpContext.Current.Server.MapPath("~/Content/images/site/galeria/thumbs");
                    var streamProvider = new GuidMultipartFormDataStreamProvider(pathImagem);
                    var imagem = new Imagem();

                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<Imagem>(t =>
                    {
                        var fileName = "";

                        //verifica se tem imagem
                        if (streamProvider.FileData.Count > 0)
                        {
                            //altera o nome da imagem
                            fileName = streamProvider.GetLocalFileName(streamProvider.FileData[0].Headers);

                            //cria o thumb
                            var combine = Path.Combine(pathImagem, fileName);
                            KalikoImage image = new KalikoImage(combine);
                            KalikoImage thumb = image.Scale(new CropScaling(150, 150));

                            image.BackgroundColor = Color.White;
                            thumb.SaveJpg(Path.Combine(pathThumb, fileName), 99);

                            //dispose das imagens
                            thumb.Dispose();
                            image.Dispose();

                            //inclui no banco de dados
                            imagem.IdSite = id;
                            imagem.Nome = fileName;
                            imagem.Url = fileName;
                            imagem.Thumbnail = fileName;
                            imagem.IsPublico = true;

                            imagem = _service.Imagem.Create(imagem);

                        }

                        return imagem;
                    });

                    return task;
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
                }
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, ex.Message));
            }
        }
コード例 #42
0
 /// <summary>Will take the source image and place it on the destination image at top left corner.</summary>
 /// <param name="image"></param>
 /// <example>
 /// 	<code title="Example" description="" lang="CS">
 /// // Place the source image on top, left of our image
 /// var sourceImage = new KalikoImage(@"C:\Img\Stamp.png");
 /// image.BlitImage(sourceImage);</code>
 /// </example>
 public void BlitImage(KalikoImage image) {
     BlitImage(image.Image, 0, 0);
 }
コード例 #43
0
    IEnumerator UploadCoroutine()
    {
        MessageBoxManager.Instance.ShowMessage(LimLanguageManager.TextDict["Layesta_Submission_Upload1"].Replace("<br>", "\n"));
        yield return(null);

        string path = WindowsDialogUtility.OpenFileDialog(LimLanguageManager.TextDict["Layesta_Submission_Load"],
#if UNITY_EDITOR
                                                          "layesta"
#else
                                                          "Layesta File|*.layesta"
#endif
                                                          , null);

        if (path == null)
        {
            yield break;
        }
        bool validate = LimLayestaReader.Validate(path);

        if (!validate)
        {
            UpdateUploadStatus("Layesta_Submission_UploadErr1");
            yield break;
        }
        byte[]       img   = LimLayestaReader.LoadBackgroundImage(path);
        MemoryStream ms    = new MemoryStream(img);
        MemoryStream msOut = new MemoryStream();

        Kaliko.ImageLibrary.KalikoImage k = new Kaliko.ImageLibrary.KalikoImage(ms);
        k = k.Scale(new Kaliko.ImageLibrary.Scaling.PadScaling(640, 360));
        k.SaveJpg(msOut, 80);
        ms.Close();
        byte[] cov = msOut.GetBuffer();
        msOut.Close();

        UpdateUploadStatus("Layesta_Submission_Upload6");
        #region Update Info
        byte[] buf = lzip.entry2Buffer(path, "info.bytes");
        ms = new MemoryStream(buf);
        BinaryReader br = new BinaryReader(ms);
        level.ShouldDisplay = ShouldDisplay.isOn;
        level.Title         = br.ReadString();
        level.Difficulties  = "";
        br.ReadString();
        int count = br.ReadInt32();
        for (int i = 0; i < count; ++i)
        {
            level.Difficulties += (br.ReadString() + ((i == count - 1) ? "" : " "));
        }
        br.ReadInt32();
        br.ReadInt32();
        if (br.BaseStream.Length > br.BaseStream.Position)
        {
            level.SongArtist = br.ReadString();
        }
        if (br.BaseStream.Length > br.BaseStream.Position)
        {
            br.ReadInt32();
        }
        br.Close();
        ms.Close();

        UnityWebRequest web = new UnityWebRequest
        {
            downloadHandler = new DownloadHandlerBuffer(),
            uploadHandler   = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(level))),
            url             = $"https://la.schwarzer.wang/layestalevel/update",
            method          = "POST"
        };
        web.SetRequestHeader("Authorization", $"Bearer {LimLayestaSubmissionManager.Instance.Bearer}");
        web.SetRequestHeader("Content-Type", $"application/json; charset=utf-8");
        web.SetRequestHeader("Accept", $"application/json; charset=utf-8");
        yield return(web.SendWebRequest());

        if (!string.IsNullOrWhiteSpace(web.error))
        {
            UpdateUploadStatus("Layesta_Submission_UploadErr2");
            yield break;
        }
        Debug.Log(web.downloadHandler.text);
        LayestaLevelResponse infoRet = JsonConvert.DeserializeObject <LayestaLevelResponse>(web.downloadHandler.text);
        if (!infoRet.Succeed)
        {
            if (infoRet.ErrorCode == ErrorCode.MissingInfo)
            {
                UpdateUploadStatus("Layesta_Submission_UploadErr3");
            }
            else
            {
                UpdateUploadStatus("Layesta_Submission_UploadErr2");
            }
            yield break;
        }
        #endregion

        UpdateUploadStatus("Layesta_Submission_Upload2");
        #region Get Layesta Upload
        web = new UnityWebRequest
        {
            downloadHandler = new DownloadHandlerBuffer(),
            url             = $"https://la.schwarzer.wang/auth/oss/upload/layesta/{level.Guid}",
            method          = "GET"
        };
        web.SetRequestHeader("Authorization", $"Bearer {LimLayestaSubmissionManager.Instance.Bearer}");
        yield return(web.SendWebRequest());

        if (web.responseCode == 401)
        {
            LimLayestaSubmissionManager.Instance.TokenInvalid();
            yield break;
        }
        if (!string.IsNullOrWhiteSpace(web.error))
        {
            yield break;
        }
        string  ret      = web.downloadHandler.text;
        JObject response = JObject.Parse(ret);
        if (!response["Succeed"].Value <bool>())
        {
            MessageBoxManager.Instance.ShowMessage(((ErrorCode)response["ErrorCode"].Value <int>()).ToString());
            yield break;
        }
        #endregion
        string layestaUrl = response["Uri"].Value <string>();
        string layestaCb  = response["Callback"].Value <string>();

        UpdateUploadStatus("Layesta_Submission_Upload3");
        #region Get Cover Upload
        web = new UnityWebRequest
        {
            downloadHandler = new DownloadHandlerBuffer(),
            url             = $"https://la.schwarzer.wang/auth/oss/upload/cover/{level.Guid}",
            method          = "GET"
        };
        web.SetRequestHeader("Authorization", $"Bearer {LimLayestaSubmissionManager.Instance.Bearer}");
        yield return(web.SendWebRequest());

        if (web.responseCode == 401)
        {
            LimLayestaSubmissionManager.Instance.TokenInvalid();
            yield break;
        }
        if (!string.IsNullOrWhiteSpace(web.error))
        {
            yield break;
        }
        ret      = web.downloadHandler.text;
        response = JObject.Parse(ret);
        if (!response["Succeed"].Value <bool>())
        {
            MessageBoxManager.Instance.ShowMessage(((ErrorCode)response["ErrorCode"].Value <int>()).ToString());
            yield break;
        }
        #endregion
        string coverUrl = response["Uri"].Value <string>();
        string coverCb  = response["Callback"].Value <string>();

        UpdateUploadStatus("Layesta_Submission_Upload4");
        #region Upload Layesta
        web = new UnityWebRequest
        {
            downloadHandler = new DownloadHandlerBuffer(),
            uploadHandler   = new UploadHandlerRaw(File.ReadAllBytes(path)),
            url             = layestaUrl,
            method          = "PUT"
        };
        web.SetRequestHeader("Content-Type", "");
        web.SetRequestHeader("User-Agent", LimLayestaSubmissionManager.Instance.Id);
        web.SetRequestHeader("x-oss-callback", layestaCb);
        ProgressBarManager.Instance.ShowProgress(() => web.isDone, () => web.uploadProgress);
        yield return(web.SendWebRequest());

        if (!string.IsNullOrWhiteSpace(web.error))
        {
            UpdateUploadStatus("Layesta_Submission_UploadErr2");
            Debug.Log(web.downloadHandler.text);
            yield break;
        }
        ret = web.downloadHandler.text;
        Debug.Log(ret);
        response = JObject.Parse(ret);
        if (response["Message"].Value <string>() != "Succeed")
        {
            UpdateUploadStatus("Layesta_Submission_UploadErr2");
            MessageBoxManager.Instance.Message.text += response["Message"].Value <string>();
            yield break;
        }
        #endregion

        UpdateUploadStatus("Layesta_Submission_Upload5");
        #region Upload Cover
        web = new UnityWebRequest
        {
            downloadHandler = new DownloadHandlerBuffer(),
            uploadHandler   = new UploadHandlerRaw(cov),
            url             = coverUrl,
            method          = "PUT"
        };
        web.SetRequestHeader("Content-Type", "");
        web.SetRequestHeader("User-Agent", LimLayestaSubmissionManager.Instance.Id);
        web.SetRequestHeader("x-oss-callback", coverCb);
        ProgressBarManager.Instance.ShowProgress(() => web.isDone, () => web.uploadProgress);
        yield return(web.SendWebRequest());

        if (!string.IsNullOrWhiteSpace(web.error))
        {
            UpdateUploadStatus("Layesta_Submission_UploadErr2");
            Debug.Log(web.downloadHandler.text);
            yield break;
        }
        ret = web.downloadHandler.text;
        Debug.Log(ret);
        response = JObject.Parse(ret);
        if (response["Message"].Value <string>() != "Succeed")
        {
            UpdateUploadStatus("Layesta_Submission_UploadErr2");
            MessageBoxManager.Instance.Message.text += response["Message"].Value <string>();
            yield break;
        }
        #endregion

        UpdateUploadStatus("Layesta_Submission_Upload7");
        LimLayestaSubmissionManager.Instance.EmptyList();
        LimLayestaSubmissionManager.Instance.Refresh();
    }
コード例 #44
0
 /// <summary>Uses the defined image as a pattern to fill the image (will be tiled if the destination image is larger than the source image)..</summary>
 /// <param name="image"></param>
 /// <example>
 /// 	<code title="Example" description="" lang="CS">
 /// // Create a new image and fill the source image all over
 /// var image = new KalikoImage(640, 480);
 /// var patternImage = new KalikoImage(@"C:\Img\Checkered.png");
 /// image.BlitFill(patternImage);</code>
 /// </example>
 public void BlitFill(KalikoImage image) {
     BlitFill(image.Image);
 }
コード例 #45
0
 internal static void DrawScaledImage(KalikoImage destinationImage, KalikoImage sourceImage, int x, int y, int width, int height)
 {
     DrawScaledImage(destinationImage.Image, sourceImage.Image, x, y, width, height);
 }
コード例 #46
0
        /// <summary>Resizes the image without any <span lang="en" id="result_box" class="short_text" xml:lang="en"><span class="hps alt-edited">consideration of the current
        /// ratio. If you wish to make a ratio locked resize use <see cref="Scale">Scale Method</see> instead.</span></span></summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <seealso cref="M:Kaliko.ImageLibrary.KalikoImage.Scale(Kaliko.ImageLibrary.Scaling.ScalingBase)"></seealso>
        public void Resize(int width, int height) {
            int newWidth = width;
            int newHeight = height;

            if (newWidth == 0 && newHeight == 0) {
                return;
            }

            if (newWidth == 0) {
                newWidth = Image.Width * newHeight / Image.Height;
            }
            else if (newHeight == 0) {
                newHeight = Image.Height * newWidth / Image.Width;
            }

            var image = new KalikoImage(newWidth, newHeight);
            DrawScaledImage(image.Image, Image, 0, 0, newWidth, newHeight);

            Image = image.Image;
        }
コード例 #47
0
        private bool IsCropValueFullImage(KalikoImage image) {
            if (_cropX == 0 && _cropY == 0 && _cropW == image.Width && _cropH == image.Height) {
                return true;
            }

            return false;
        }