예제 #1
0
        public void MagickImageTgaOrigin()
        {
            using (var originLeftBottom = new MagickImage(originLeftBottomTgaPath))
                using (var originLeftTop = new MagickImage(originLeftTopTgaPath))
                    using (var png = new MagickImage(albedo1024pxPngPath))
                    {
                        // Check loaded orientation
                        Assert.AreNotEqual(originLeftBottom.Orientation, originLeftTop.Orientation);
                        Assert.AreEqual(OrientationType.BottomLeft, originLeftBottom.Orientation);
                        Assert.AreEqual(OrientationType.TopLeft, originLeftTop.Orientation);

                        // Check format
                        Assert.AreEqual(MagickFormat.Tga, originLeftBottom.Format);
                        Assert.AreEqual(MagickFormat.Tga, originLeftTop.Format);

                        // Compare pixels with png
                        Assert.AreNotEqual(0.0, png.Compare(originLeftBottom).MeanErrorPerPixel);
                        originLeftBottom.AutoOrient();
                        Assert.AreEqual(0.0, png.Compare(originLeftBottom).MeanErrorPerPixel);

                        Assert.AreEqual(0.0, png.Compare(originLeftTop).MeanErrorPerPixel);
                        originLeftTop.AutoOrient();
                        Assert.AreEqual(0.0, png.Compare(originLeftTop).MeanErrorPerPixel);
                    }
        }
예제 #2
0
        public override Task <BitmapSource> GetRenderedFrame(int index)
        {
            // the first image is always returns synchronously.
            if (index == 0 && _thumbnail != null)
            {
                return(new Task <BitmapSource>(() => _thumbnail));
            }

            return(new Task <BitmapSource>(() =>
            {
                using (var image = new MagickImage(_path))
                {
                    try
                    {
                        image.AddProfile(ColorProfile.SRGB);
                    }
                    catch (MagickResourceLimitErrorException)
                    {
                        // https://github.com/xupefei/QuickLook/issues/292: ColorspaceColorProfileMismatch
                    }

                    image.Density = new Density(Math.Floor(image.Density.X), Math.Floor(image.Density.Y));
                    image.AutoOrient();

                    var bs = image.ToBitmapSource();
                    bs.Freeze();
                    return bs;
                }
            }));
        }
예제 #3
0
        public static Image <TPixel> DecodeWithMagick <TPixel>(FileInfo fileInfo)
            where TPixel : unmanaged, ImageSharp.PixelFormats.IPixel <TPixel>
        {
            Configuration configuration = Configuration.Default.Clone();

            configuration.PreferContiguousImageBuffers = true;
            using (var magickImage = new MagickImage(fileInfo))
            {
                magickImage.AutoOrient();
                var result = new Image <TPixel>(configuration, magickImage.Width, magickImage.Height);

                Assert.True(result.DangerousTryGetSinglePixelMemory(out Memory <TPixel> resultPixels));

                using (IUnsafePixelCollection <ushort> pixels = magickImage.GetPixelsUnsafe())
                {
                    byte[] data = pixels.ToByteArray(PixelMapping.RGBA);

                    PixelOperations <TPixel> .Instance.FromRgba32Bytes(
                        configuration,
                        data,
                        resultPixels.Span,
                        resultPixels.Length);
                }

                return(result);
            }
        }
        public string Execute(FileItem item, string infile, string dest, ValuePairEnumerator configData)
        {
            var conf = new RotateTransformViewModel(configData);

            // Read from file
            using (MagickImage image = new MagickImage(infile))
            {
                image.BackgroundColor = new MagickColor(Color.Black);
                if (conf.AutoRotate)
                {
                    ExifProfile profile = image.GetExifProfile();
                    image.AutoOrient();
                    profile.SetValue(ExifTag.Orientation, (UInt16)0);
                }
                if (conf.Angle > 0)
                {
                    image.Rotate(conf.Angle);
                }

                if (conf.FlipHorizontal)
                {
                    image.Flop();
                }

                if (conf.FlipVertical)
                {
                    image.Flip();
                }

                image.Format = MagickFormat.Jpeg;
                // Save the result
                image.Write(dest);
            }
            return(dest);
        }
예제 #5
0
        /// <summary>
        /// Get MagickImage from Unity Texture.
        /// </summary>
        /// <param name="texture">Unity Texture.</param>
        /// <returns>Loaded MagickImage.</returns>
        internal static MagickImage GetMagickImage(Texture texture)
        {
            if (texture == null)
            {
                return(null);
            }

            if (texture.GetType() == typeof(RenderTexture))
            {
                return(new MagickImage(MagickColors.Black, 1, 1));
            }

            var path = AssetDatabase.GetAssetPath(texture);

            try
            {
                if (path == "Resources/unity_builtin_extra")
                {
                    return(UnityBuiltinExtraToMagickImage(texture as Texture2D));
                }
                var image = new MagickImage(path);
                if (image.Format == MagickFormat.Tga)
                {
                    image.AutoOrient();
                }
                return(image);
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to load \"{path}\" as MagickImage: {e.Message}");
            }
        }
예제 #6
0
    public static async Task UploadImage(string storageConnectionString, string containerName, byte[] fileBytes, bool isThumbnail)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

        var blobClient = storageAccount.CreateCloudBlobClient();
        var container  = blobClient.GetContainerReference(containerName);

        await container.CreateIfNotExistsAsync();

        await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

        CloudBlockBlob blockBlob = container.GetBlockBlobReference("test"); //replace with userId

        MagickImage image = new MagickImage(fileBytes);

        image.AutoOrient();

        if (isThumbnail)
        {
            var thumbnailBytes = CreateThumbNail(image);
            await blockBlob.UploadFromByteArrayAsync(thumbnailBytes, 0, thumbnailBytes.Length);
        }
        else
        {
            byte[] bytes = image.ToByteArray();
            await blockBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
        }
    }
예제 #7
0
        public async Task <ActionResult <Attachment> > UploadAvatar(IFormFile file)
        {
            try
            {
                var extension = Path.GetExtension(file.FileName);

                if (extension.ToLower().StartsWith(".jp") || extension.ToLower().StartsWith(".png"))
                {
                    var dirPath = UploadPath();
                    var path    = Path.Combine(dirPath, file.FileName);

                    if (System.IO.File.Exists(path))
                    {
                        dirPath = CreateRandomNameDirectory();
                        path    = Path.Combine(dirPath, file.FileName);
                    }

                    await using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    using (MagickImage image = new MagickImage(path))
                    {
                        image.AutoOrient();

                        if (image.Width > image.Height)
                        {
                            image.Crop(image.Height, image.Height, Gravity.Center);
                            image.RePage();
                        }
                        else
                        {
                            var n = new MagickGeometry(0, -image.Height / 10, image.Width, image.Width);
                            image.Crop(n, Gravity.Center);
                            image.RePage();
                        }

                        if (image.Width > 300)
                        {
                            image.Resize(240, 0);
                        }

                        image.Quality = 60;
                        image.Write(path);
                    }

                    return(Ok(path));
                }

                return(BadRequest());
            }
            catch (NotSupportedException ex)
            {
                return(BadRequest(new { Message = $"Error: {ex.Message}" }));
            }
        }
예제 #8
0
        public override Task <BitmapSource> GetRenderedFrame(int index)
        {
            var fullSize = Meta.GetSize();

            return(new Task <BitmapSource>(() =>
            {
                var settings = new MagickReadSettings
                {
                    BackgroundColor = MagickColors.None,
                    Defines = new DngReadDefines
                    {
                        OutputColor = DngOutputColor.SRGB,
                        UseCameraWhitebalance = true,
                        DisableAutoBrightness = false
                    }
                };

                try
                {
                    using (var mi = new MagickImage(Path.LocalPath, settings))
                    {
                        if (SettingHelper.Get("UseColorProfile", false, "QuickLook.Plugin.ImageViewer"))
                        {
                            if (mi.ColorSpace == ColorSpace.RGB || mi.ColorSpace == ColorSpace.sRGB || mi.ColorSpace == ColorSpace.scRGB)
                            {
                                mi.SetProfile(ColorProfile.SRGB);
                                if (ContextObject.ColorProfileName != null)
                                {
                                    mi.SetProfile(new ColorProfile(ContextObject.ColorProfileName)); // map to monitor color
                                }
                            }
                        }

                        mi.AutoOrient();

                        if (mi.Width != (int)fullSize.Width || mi.Height != (int)fullSize.Height)
                        {
                            mi.Resize((int)fullSize.Width, (int)fullSize.Height);
                        }

                        mi.Density = new Density(DisplayDeviceHelper.DefaultDpi * DisplayDeviceHelper.GetCurrentScaleFactor().Horizontal,
                                                 DisplayDeviceHelper.DefaultDpi * DisplayDeviceHelper.GetCurrentScaleFactor().Vertical);

                        var img = mi.ToBitmapSourceWithDensity();

                        img.Freeze();
                        return img;
                    }
                }
                catch (Exception e)
                {
                    ProcessHelper.WriteLog(e.ToString());
                    return null;
                }
            }));
        }
예제 #9
0
 public void Normalize()
 {
     ThrowIfDisposed();
     _native.AutoOrient();
     try
     {
         _native.GetExifProfile()?.SetValue(ExifTag.Orientation, (ushort)0);
     }
     catch { }
 }
예제 #10
0
        public void GetAnimator(ObjectAnimationUsingKeyFrames animator, string path)
        {
            using (var image = new MagickImage(path))
            {
                image.Density = new Density(Math.Floor(image.Density.X), Math.Floor(image.Density.Y));
                image.AutoOrient();

                animator.KeyFrames.Add(new DiscreteObjectKeyFrame(image.ToBitmapSource(), TimeSpan.Zero));
                animator.Duration = Duration.Forever;
            }
        }
예제 #11
0
 private static void ConvertLowres(string lowresDirectory, IFormFile image, string imageName, string imageExtension)
 {
     using (MagickImage imageFile = new MagickImage(GetFormImageToByte(image)))
     {
         MagickGeometry reSize = new MagickGeometry(new Percentage(90), new Percentage(90));
         imageFile.AutoOrient();
         reSize.IgnoreAspectRatio = false;
         imageFile.Resize(reSize);
         imageFile.Write(Path.Combine(lowresDirectory, imageName + imageExtension));
     }
 }
예제 #12
0
 private static void ConvertThumbnail(string thumbnailDirectory, IFormFile image, string imageName, string imageExtension)
 {
     using (MagickImage imageFile = new MagickImage(GetFormImageToByte(image)))
     {
         MagickGeometry reSize = new MagickGeometry(300);
         imageFile.AutoOrient();
         reSize.IgnoreAspectRatio = false;
         imageFile.Resize(reSize);
         imageFile.Write(Path.Combine(thumbnailDirectory, imageName + imageExtension));
     }
 }
예제 #13
0
        public override Task <BitmapSource> GetRenderedFrame(int index)
        {
            var fullSize = Meta.GetSize();

            return(new Task <BitmapSource>(() =>
            {
                var settings = new MagickReadSettings
                {
                    BackgroundColor = MagickColors.None,
                    Defines = new DngReadDefines
                    {
                        OutputColor = DngOutputColor.SRGB,
                        UseCameraWhitebalance = true,
                        DisableAutoBrightness = false
                    }
                };

                try
                {
                    using (var mi = new MagickImage(Path.LocalPath, settings))
                    {
                        var profile = mi.GetColorProfile();
                        if (mi.ColorSpace == ColorSpace.RGB || mi.ColorSpace == ColorSpace.sRGB ||
                            mi.ColorSpace == ColorSpace.scRGB)
                        {
                            if (profile?.Description != null && !profile.Description.Contains("sRGB"))
                            {
                                mi.SetProfile(ColorProfile.SRGB);
                            }
                        }

                        mi.AutoOrient();

                        if (mi.Width != (int)fullSize.Width || mi.Height != (int)fullSize.Height)
                        {
                            mi.Resize((int)fullSize.Width, (int)fullSize.Height);
                        }

                        mi.Density = new Density(DpiHelper.DefaultDpi * DpiHelper.GetCurrentScaleFactor().Horizontal,
                                                 DpiHelper.DefaultDpi * DpiHelper.GetCurrentScaleFactor().Vertical);

                        var img = mi.ToBitmapSourceWithDensity();

                        img.Freeze();
                        return img;
                    }
                }
                catch (Exception e)
                {
                    ProcessHelper.WriteLog(e.ToString());
                    return null;
                }
            }));
        }
예제 #14
0
        public void GetAnimator(ObjectAnimationUsingKeyFrames animator, string path)
        {
            // set dcraw.exe for Magick.NET
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            using (var image = new MagickImage(path))
            {
                image.AutoOrient();

                animator.KeyFrames.Add(new DiscreteObjectKeyFrame(image.ToBitmapSource(), TimeSpan.Zero));
                animator.Duration = Duration.Forever;
            }

            Directory.SetCurrentDirectory(App.AppPath);
        }
예제 #15
0
파일: State.cs 프로젝트: tonyp7/ImageView
        private bool loadPicture(IEntry entry)
        {
            this.Dispose();
            this.activeEntry = entry;

            Exception exception = null;

            //load image
#if DEBUG
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
#endif
            Stream stream = entry.GetStream();
            try
            {
                this.nativeImage = new ImageMagick.MagickImage(stream);
            }
            catch (Exception e)
            {
                this.nativeImage = new MagickImage(Properties.Resources.error);
                exception        = e;
            }
            stream.Dispose();
#if DEBUG
            stopWatch.Stop();
            System.Diagnostics.Debug.WriteLine(String.Format("Loading image in {0} ms", stopWatch.Elapsed.Milliseconds));
#endif

            //convert to bitmap
            if (Settings.Get.Display.AutoRotate && nativeImage.Orientation != OrientationType.Undefined)
            {
                nativeImage.AutoOrient();
            }
            bitmap = nativeImage.ToBitmap();


            //Add loaded file to history if necessary
            TextRepresentationEntry tre = activeEntry.ToText();
            Settings.Get.History.AddFile(tre);

            //if there was an exception throw it
            if (exception != null)
            {
                throw new ImageViewLoadException(exception, entry);
            }

            return(true);
        }
예제 #16
0
        static void Main(string[] args)
        {
            using (var image = new MagickImage(@"https://github.com/recurser/exif-orientation-examples/blob/master/Landscape_2.jpg?raw=true"))
            {
                // set default thumbnail to recommended size of 100px by 100px
                var            thumbnailSize = 100;
                var            resize        = new MagickGeometry();
                MagickGeometry crop          = null;

                if (image.Height == image.Width)
                {
                    // if aspect ratio is 1:1 just scale down to 100px
                    resize.Width = thumbnailSize;
                }
                else
                {
                    // resize to shorter dimension to 100px and then crop equal amounts off other dimension
                    crop = new MagickGeometry();
                    if (image.Height < image.Width)
                    {
                        resize.Height = thumbnailSize;
                        var resizedWidth = Convert.ToInt32((double)resize.Height / image.Height * image.Width);
                        crop.Width = thumbnailSize;
                        crop.X     = (resizedWidth - thumbnailSize) / 2;
                    }
                    if (image.Width < image.Height)
                    {
                        resize.Width = thumbnailSize;
                        var resizedHeight = Convert.ToInt32((double)resize.Width / image.Width * image.Height);
                        crop.Height = thumbnailSize;
                        crop.Y      = (resizedHeight - thumbnailSize) / 2;
                    }
                }

                // apply transformations
                image.AdaptiveResize(resize);
                if (crop != null)
                {
                    image.Crop(crop);
                }

                // auto orient using exif data
                image.AutoOrient();

                // make request using info from thumbnail_upload_request with buffer
            }
        }
예제 #17
0
        public async Task <string> UploadBlob(string blobContainer, IFormFile file, string directoryName, bool isThumbnail)
        {
            int    fileNameStartLocation = file.FileName.LastIndexOf("\\") + 1;
            string fileName = file.FileName.Substring(fileNameStartLocation);

            CloudBlobContainer container = _client.GetContainerReference(blobContainer);
            await container.CreateIfNotExistsAsync();

            await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(directoryName + @"\" + fileName);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

            MagickImage image = new MagickImage(file.OpenReadStream());

            image.AutoOrient();

            if (isThumbnail)
            {
                if (image.Width > image.Height)
                {
                    image.Resize((new MagickGeometry()
                    {
                        Height = 200, Width = 340, FillArea = true
                    }));
                }
                else
                {
                    image.Extent(new MagickGeometry()
                    {
                        Height = 200, Width = 340, FillArea = false, Greater = true, Less = true
                    }, Gravity.Center);
                }


                //image.AdaptiveResize(new MagickGeometry() { Width = 340, Height = 200, FillArea = true });
                image.Crop(340, 200, Gravity.Center);
            }

            await memoryStream.WriteAsync(image.ToByteArray(), 0, image.ToByteArray().Count());

            memoryStream.Position = 0;
            await blockBlob.UploadFromStreamAsync(memoryStream);

            return(blockBlob.Uri.AbsoluteUri);
        }
예제 #18
0
            public void ShouldRotateTheImage()
            {
                using (var image = new MagickImage(Files.FujiFilmFinePixS1ProPNG))
                {
                    Assert.Equal(600, image.Width);
                    Assert.Equal(400, image.Height);
                    Assert.Equal(OrientationType.TopLeft, image.Orientation);

                    image.Orientation = OrientationType.RightTop;

                    image.AutoOrient();

                    Assert.Equal(400, image.Width);
                    Assert.Equal(600, image.Height);
                    Assert.Equal(OrientationType.TopLeft, image.Orientation);
                }
            }
예제 #19
0
        public async Task UploadAsync(int id, IFormFile file, bool isThumbnail)
        {
            int    fileNameStartLocation = file.FileName.LastIndexOf("\\") + 1;
            string fileName = file.FileName.Substring(fileNameStartLocation);

            if (isThumbnail)
            {
                fileName = $"thumbnail-{fileName}";
            }

            byte[] fileBytes;

            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);

                fileBytes = ms.ToArray();
            }

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable(Constants.BLOB_STORAGE_CONNECTIONSTRING));

            var blobClient = storageAccount.CreateCloudBlobClient();
            var container  = blobClient.GetContainerReference(id.ToString());

            await container.CreateIfNotExistsAsync();

            await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            MagickImage image = new MagickImage(fileBytes);

            image.AutoOrient();

            if (isThumbnail)
            {
                var thumbnailBytes = CreateThumbNail(image);
                await blockBlob.UploadFromByteArrayAsync(thumbnailBytes, 0, thumbnailBytes.Length);
            }
            else
            {
                byte[] bytes = image.ToByteArray();
                await blockBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length);
            }
        }
예제 #20
0
        public async Task <PhotoUploadDto> Upload(IFormFile file, IFilePath filePath)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            string randomGuid = Guid.NewGuid().ToString();

            var imageExtension = Path.GetExtension(file.FileName);

            _photoOriginalName = randomGuid + imageExtension;
            _photoOriginalPath = Path.Combine(_env.ContentRootPath, filePath.Path, _photoOriginalName);

            using (var stream = new FileStream(_photoOriginalPath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // Read from file
            using (MagickImage image = new MagickImage(_photoOriginalPath))
            {
                var photoThumbWidth  = AppConstants.ProfilePhotoThumbSizeWidth.ToString();
                var photoThumbHeight = AppConstants.ProfilePhotoThumbSizeHeight.ToString();
                _photoThumbName = $"{randomGuid}-thumb-{photoThumbWidth}x{photoThumbHeight}{imageExtension}";
                _photoThumbPath = Path.Combine(_env.ContentRootPath, filePath.Path, _photoThumbName);

                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);
                image.AutoOrient();

                // Save the result
                image.Write(_photoThumbPath);
            }

            return(new PhotoUploadDto
            {
                PhotoOriginalPath = Path.Combine(filePath.PublicPath, _photoOriginalName),
                PhotoThumbPath = Path.Combine(filePath.PublicPath, _photoThumbName)
            });
        }
예제 #21
0
        /// <summary>
        /// Функция сжимает загружаемую картинку для экономия места на
        /// сервер и быстрой загрузки их на мобильных устройствах
        /// </summary>
        /// <param name="InputPath">Путь WebRootPath/img</param>
        /// <param name="FileName">Имя файла из базы данных</param>
        /// <param name="File">Полный путь до файла</param>
        public static async Task Compress(string InputPath, string FileName, string File)
        {
            using (var photo = new MagickImage(File))
            {
                photo.AutoOrient();

                photo.Resize(l_size, 0);
                photo.Quality = l_quality;
                photo.Strip();
                var Photo = Path.Combine(InputPath, "Photo", FileName);
                photo.Write(Photo);

                photo.Resize(s_size, 0);
                photo.Quality = s_quality;
                photo.Strip();
                var Icon = Path.Combine(InputPath, "Icons", FileName);
                photo.Write(Icon);
            }
        }
        private async Task OrientAndSetMetadataAsync(MagickImage image, ICloudBlockBlob output, CancellationToken cancellationToken, ILogger logger, Stopwatch sw)
        {
            if (image.Orientation != OrientationType.Undefined && image.Orientation != OrientationType.TopLeft)
            {
                image.AutoOrient();
                using (var outputStream = await output.OpenWriteAsync(cancellationToken))
                {
                    image.Write(outputStream);
                    SetMetadata(image, output);
                    await Task.Factory.FromAsync(outputStream.BeginCommit(null, null), outputStream.EndCommit);
                }

                logger.Info("Orient: " + sw.ElapsedMilliseconds);
            }
            else
            {
                await SetAndSaveMetadata(output, image);
            }
        }
        private void bwImageProcess_DoWork(object sender, DoWorkEventArgs e)
        {
            if (this.m_processQueue.Count > 0)
            {
                string fname = "";
                lock (this.m_syncObject)
                {
                    fname = m_processQueue.Dequeue();
                }

                byte[] tempImg = File.ReadAllBytes(fname);
                string ocrText = "";

                MagickReadSettings settings = new MagickReadSettings();
                using (MagickImage image = new MagickImage(tempImg, settings))
                {
                    image.Quality = scannedQuality;
                    image.Deskew(new Percentage(100));
                    image.Trim();
                    image.AutoOrient();
                    File.Delete(fname);
                    image.Write(fname);

                    Bitmap          bmp             = Grayscale.CommonAlgorithms.BT709.Apply(image.ToBitmap());
                    Threshold       thresholdFilter = new Threshold(127);
                    Bitmap          searchOcr       = thresholdFilter.Apply(bmp);
                    TesseractEngine engine          = new TesseractEngine("tessdata", "eng", EngineMode.Default);
                    Page            page            = engine.Process(searchOcr);
                    ocrText = page.GetText();
                }


                fileList.Add(fname);
                DataRow r = dtDoc.NewRow();
                r["DocFilename"] = fname;
                r["DocValue"]    = "0";
                r["DocSize"]     = string.Format("{0:n0} KB", Math.Round((double)new FileInfo(fname).Length / 1024));
                r["DocOcr"]      = ocrText;
                dtDoc.Rows.Add(r);
                e.Result = r;
            }
        }
예제 #24
0
        public void AddPhotoToDb(UploadedPhoto uploadedPhoto, FamilyArchiveContext context)
        {
            if (context.Photos.Where(p => p.Name == uploadedPhoto.filename && !p.IsThumbnail).FirstOrDefault() == null)
            {
                byte[] Base64Photo;
                if (uploadedPhoto.fileContent.Length > 1000000)
                {
                    MemoryStream memoryStream = new MemoryStream(uploadedPhoto.fileContent);

                    ImageOptimizer imageOptimizer = new ImageOptimizer();
                    imageOptimizer.LosslessCompress(memoryStream);

                    using (MagickImage sprite = new MagickImage(memoryStream))
                    {
                        sprite.Quality = 100;

                        sprite.AutoOrient();

                        if (sprite.Width > sprite.Height)
                        {
                            sprite.Resize(1280, 960);
                        }
                        else
                        {
                            sprite.Resize(960, 1280);
                        }

                        Base64Photo = Encoding.ASCII.GetBytes(sprite.ToBase64());
                    }
                }
                else
                {
                    Base64Photo = Encoding.ASCII.GetBytes(Convert.ToBase64String(uploadedPhoto.fileContent));
                }

                Photos DbPhotoToAdd = new Photos();
                DbPhotoToAdd.Name        = uploadedPhoto.filename;
                DbPhotoToAdd.IsThumbnail = false;
                DbPhotoToAdd.PhotoBase64 = Base64Photo;
                context.Photos.Add(DbPhotoToAdd);
            }
        }
        // Retrieves image file from the given path and fixes
        // potential orientation bug from images taken on a cellphone
        static public void ImageOrient(string path)
        {
            try
            {
                // Read from file
                using MagickImage image = new MagickImage(path);
                image.AutoOrient();

                image.Format = MagickFormat.Png;
                // Save the result
                image.Write(path);
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Debug.Write("Unexpected Error: " + e.Message);
                Debug.Write("Details: ");
                Debug.Write(e.ToString());
            };
        }
예제 #26
0
        public static Image <TPixel> DecodeWithMagick <TPixel>(Configuration configuration, FileInfo fileInfo)
            where TPixel : unmanaged, ImageSharp.PixelFormats.IPixel <TPixel>
        {
            using var magickImage = new MagickImage(fileInfo);
            magickImage.AutoOrient();
            var result = new Image <TPixel>(configuration, magickImage.Width, magickImage.Height);

            Assert.True(result.TryGetSinglePixelSpan(out Span <TPixel> resultPixels));

            using IUnsafePixelCollection <ushort> pixels = magickImage.GetPixelsUnsafe();
            byte[] data = pixels.ToByteArray(PixelMapping.RGBA);

            PixelOperations <TPixel> .Instance.FromRgba32Bytes(
                configuration,
                data,
                resultPixels,
                resultPixels.Length);

            return(result);
        }
예제 #27
0
        public static async Task <ImageViewModel> BuildViewModelFromPath(string path)
        {
            var realPath = await Task.Run <Tuple <string, bool> >(async() =>
            {
                if (path.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase) ||
                    path.EndsWith(".jpeg", StringComparison.InvariantCultureIgnoreCase))
                {
                    using (var img = new MagickImage(path))
                    {
                        img.AutoOrient();   // Fix orientation
                        img.Strip();        // remove all EXIF information

                        if (img.Width > 1920 || img.Height > 1920)
                        {
                            if (img.Width > img.Height)
                            {
                                img.Scale(1920, 1080);
                            }
                            else
                            {
                                img.Scale(1080, 1920);
                            }
                        }

                        var tempName = System.IO.Path.GetTempFileName() + ".jpg";
                        img.Write(tempName);

                        return(new Tuple <string, bool>(tempName, true));
                    }
                }
                else
                {
                    return(new Tuple <string, bool>(path, false));
                }
            });

            return(new ImageViewModel(realPath.Item1)
            {
                IsTempFile = realPath.Item2
            });
        }
예제 #28
0
        public override Task <BitmapSource> GetRenderedFrame(int index)
        {
            // the first image is always returns synchronously.
            if (index == 0 && _thumbnail != null)
            {
                return(new Task <BitmapSource>(() => _thumbnail));
            }

            return(new Task <BitmapSource>(() =>
            {
                using (var image = new MagickImage(_path))
                {
                    image.AddProfile(ColorProfile.SRGB);
                    image.Density = new Density(Math.Floor(image.Density.X), Math.Floor(image.Density.Y));
                    image.AutoOrient();

                    var bs = image.ToBitmapSource();
                    bs.Freeze();
                    return bs;
                }
            }));
        }
예제 #29
0
        public override Task <BitmapSource> GetRenderedFrame(int index)
        {
            var fullSize = Meta.GetSize();

            return(new Task <BitmapSource>(() =>
            {
                try
                {
                    using (var mi = new MagickImage(Path))
                    {
                        var profile = mi.GetColorProfile();
                        if (profile?.Description != null && !profile.Description.Contains("sRGB"))
                        {
                            mi.SetProfile(ColorProfile.SRGB);
                        }

                        mi.AutoOrient();

                        if (mi.Width != (int)fullSize.Width || mi.Height != (int)fullSize.Height)
                        {
                            mi.Resize((int)fullSize.Width, (int)fullSize.Height);
                        }

                        mi.Density = new Density(DpiHelper.DefaultDpi * DpiHelper.GetCurrentScaleFactor().Horizontal,
                                                 DpiHelper.DefaultDpi * DpiHelper.GetCurrentScaleFactor().Vertical);

                        var img = mi.ToBitmapSource(BitmapDensity.Use);

                        img.Freeze();
                        return img;
                    }
                }
                catch (Exception e)
                {
                    ProcessHelper.WriteLog(e.ToString());
                    return null;
                }
            }));
        }
예제 #30
0
        public async Task Enrich(Photo photo, SourceDataDto source)
        {
            using (var stream = new MemoryStream())
            {
                using (var image = new MagickImage(source.AbsolutePath))
                {
                    image.AutoOrient();
                    source.OriginalImage = image.Clone();
                    photo.Height         = image.Height;
                    photo.Width          = image.Width;
                    photo.Orientation    = (int?)image.Orientation;
                    ImageHelper.ResizeImage(image, out var scale);
                    image.Format = MagickFormat.Jpg;
                    await image.WriteAsync(stream);

                    photo.Scale         = scale;
                    source.PreviewImage = image.Clone();
                }

                photo.PreviewImage = stream.ToArray();
            }
        }