Ejemplo n.º 1
0
 public static void Compress(string image)
 {
     byte[] bytes = Convert.FromBase64String(image.Split(',')[1]);
     using (Stream stream = new MemoryStream(bytes))
     {
         const int size = 150;
         using (var original = FreeImageBitmap.FromStream(stream))
         {
             int width, height;
             if (original.Width > original.Height)
             {
                 width  = size;
                 height = original.Height * size / original.Width;
             }
             else
             {
                 width  = original.Width * size / original.Height;
                 height = size;
             }
             var    resized   = new FreeImageBitmap(original, width, height);
             Stream newStream = new MemoryStream();
             resized.Save(newStream, FREE_IMAGE_FORMAT.FIF_JPEG);
             var newBytes = ReadFully(newStream);
             var contents = new StreamContent(new MemoryStream(newBytes));
         }
     }
 }
Ejemplo n.º 2
0
        private string UploadFile(Stream stream, string url = "")
        {
            try
            {
                using (var image = FreeImageBitmap.FromStream(stream))
                {
                    using (MemoryStream newStream = new MemoryStream())
                    {
                        image.Save(newStream, FREE_IMAGE_FORMAT.FIF_PNG, FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION | FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_SPEED);

                        CloudStorageAccount storage = CloudStorageAccount.Parse(StorageOptions.ConnectionString);
                        var blobClient    = storage.CreateCloudBlobClient();
                        var blobContainer = blobClient.GetContainerReference(StorageOptions.ContainerName);
                        blobContainer.CreateIfNotExistsAsync().Wait();
                        var blobRef = blobContainer.GetBlockBlobReference(GenerateFileNmae(url));
                        blobRef.Properties.ContentType = "image/png";
                        blobRef.UploadFromByteArrayAsync(newStream.GetBuffer(), 0, newStream.GetBuffer().Length).Wait();


                        return(blobRef.Uri.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                return("");
            }
        }
Ejemplo n.º 3
0
 public void FreeImageBufferBuffer()
 {
     using var ims     = new MemoryStream(buffer);
     using var image   = FreeImageBitmap.FromStream(ims);
     using var resized = new FreeImageBitmap(image, Width, Height);
     using var oms     = new MemoryStream();
     resized.Save(oms, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD);
     oms.ToArray();
 }
        public RadBitmap Import(Stream stream)
        {
            FreeImageBitmap freeImageBitmap;

            using (stream)
            {
                freeImageBitmap = FreeImageBitmap.FromStream(stream);
            }

            return(freeImageBitmap.ToBitmap().ToRadBitmap());
        }
Ejemplo n.º 5
0
        private FreeImageBitmap CreateFreeImageDirectly()
        {
            FreeImageBitmap fi;

            using (DllManager dllManager = new DllManager("FreeImage.dll"))
            {
                if (!CopySelection())
                {
                    return(null);
                }
                MemoryStream data = Clipboard.GetData("PNG") as MemoryStream;
                Logger.Info("CreateFreeImageDirectly: Create FreeImage bitmap");
                fi = FreeImageBitmap.FromStream(data);
            }
            return(fi);
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Edit(long id, ComponentType componentType, IFormFile imageFile)
        {
            if (id != componentType.ComponentTypeId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (imageFile.Length > 0)
                    {
                        var stream    = imageFile.OpenReadStream();
                        var bitmap    = FreeImageBitmap.FromStream(stream);
                        var thumbnail = bitmap.GetThumbnailImage(1000, true);

                        using (var m = new MemoryStream())
                        {
                            bitmap.Save(m, format: bitmap.ImageFormat);
                            componentType.Image.ImageData = m.ToArray();
                        }
                        using (var m = new MemoryStream())
                        {
                            thumbnail.Save(m, format: FREE_IMAGE_FORMAT.FIF_JPEG);
                            componentType.Image.Thumbnail = m.ToArray();
                        }
                    }

                    _context.Update(componentType);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ComponentTypeExists(componentType.ComponentTypeId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(componentType));
        }
Ejemplo n.º 7
0
        public static Response GetPageImage(Guid id, int page, int width, int height, IResponseFormatter response)
        {
            // Restrict access to the FreeImage library to one thread at a time.
            lock (lockThis)
            {
                int  max_width  = 0;
                int  max_height = 0;
                bool thumbnail  = !(width == -1 && height == -1);
                bool processed  = false;

                string filename = string.Format("{0}-p{1}-w{2}-h{3}.jpg", id, page, width, height);

                if (thumbnail)
                {
                    MemoryStream cachestream = ImageCache.Instance.LoadFromCache(filename, true);
                    // Cached thumbnails are assumed to be in the correct format and adhere to the size/format restrictions of the ipad.
                    if (cachestream != null)
                    {
                        return(response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg")));
                    }
                }
                else
                {
                    // Check if a processed (rescaled and/or progressive) image is cached.
                    string       processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page);
                    MemoryStream cachestream        = ImageCache.Instance.LoadFromCache(processed_filename, false);
                    if (cachestream != null)
                    {
                        return(response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg")));
                    }
                }

                MemoryStream stream = null;

                // Check if original image is in the cache.
                string org_filename = string.Format("{0}-p{1}.jpg", id, page);
                stream = ImageCache.Instance.LoadFromCache(org_filename, false);

                if (stream == null)
                {
                    // Image is not in the cache, get it via ComicRack.
                    var bytes = GetPageImageBytes(id, page);
                    if (bytes == null)
                    {
                        return(HttpStatusCode.NotFound);
                    }

                    stream = new MemoryStream(bytes);

                    // Always save the original page to the cache
                    ImageCache.Instance.SaveToCache(org_filename, stream, false);
                }

                stream.Seek(0, SeekOrigin.Begin);

            #if USE_GDI
                Bitmap bitmap        = new Bitmap(stream, false);
                int    bitmap_width  = (int)bitmap.Width;
                int    bitmap_height = (int)bitmap.Height;
            #elif USE_DIB
                FIBITMAP dib = FreeImage.LoadFromStream(stream);
                if (dib == null)
                {
                    Console.WriteLine("Loading bitmap failed. Aborting.");
                    // Check whether there was an error message.
                    return(HttpStatusCode.InternalServerError);
                }
                int bitmap_width  = (int)FreeImage.GetWidth(dib);
                int bitmap_height = (int)FreeImage.GetHeight(dib);
            #elif USE_FIB
                FreeImageBitmap fib = FreeImageBitmap.FromStream(stream, false);
                if (fib == null)
                {
                    Console.WriteLine("Loading bitmap failed. Aborting.");
                    // Check whether there was an error message.
                    return(HttpStatusCode.InternalServerError);
                }

                int bitmap_width  = (int)fib.Width;
                int bitmap_height = (int)fib.Height;
            #endif

                if (ImageCache.Instance.use_max_dimension)
                {
                    int mw, mh;

                    if (bitmap_width >= bitmap_height)
                    {
                        mw = ImageCache.Instance.max_dimension_long;
                        mh = ImageCache.Instance.max_dimension_short;
                    }
                    else
                    {
                        mw = ImageCache.Instance.max_dimension_short;
                        mh = ImageCache.Instance.max_dimension_long;
                    }

                    if (bitmap_width > mw || bitmap_height > mh)
                    {
                        double scaleW = (double)mw / (double)bitmap_width;
                        double scaleH = (double)mh / (double)bitmap_height;
                        double scale  = Math.Min(scaleW, scaleH);

                        max_width  = (int)Math.Floor(scale * bitmap_width);
                        max_height = (int)Math.Floor(scale * bitmap_height);
                    }
                    else
                    {
                        max_width  = bitmap_width;
                        max_height = bitmap_height;
                    }
                }
                else
                // Check if the image dimensions exceeds the maximum image dimensions
                if ((bitmap_width * bitmap_height) > ImageCache.Instance.maximum_imagesize)
                {
                    max_width  = (int)Math.Floor(Math.Sqrt((double)bitmap_width / (double)bitmap_height * (double)ImageCache.Instance.maximum_imagesize));
                    max_height = (int)Math.Floor((double)max_width * (double)bitmap_height / (double)bitmap_width);
                }
                else
                {
                    max_width  = bitmap_width;
                    max_height = bitmap_height;
                }

                // Calculate the dimensions of the returned image.
                int result_width  = width;
                int result_height = height;

                if (result_width == -1 && result_height == -1)
                {
                    result_width  = max_width;
                    result_height = max_height;
                }
                else
                {
                    if (result_width == -1)
                    {
                        result_height = Math.Min(max_height, result_height);
                        double ratio = (double)result_height / (double)max_height;
                        result_width = (int)Math.Floor(((double)max_width * ratio));
                    }
                    else
                    if (result_height == -1)
                    {
                        result_width = Math.Min(max_width, result_width);
                        double ratio = (double)result_width / (double)max_width;
                        result_height = (int)Math.Floor(((double)max_height * ratio));
                    }
                }

                // TODO: do this per requesting target device instead of using one global setting.

                // Resize ?
                if (result_width != bitmap_width || result_height != bitmap_height)
                {
                    processed = true;

              #if USE_DIB || USE_FIB
                    //FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_BICUBIC;
                    FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_LANCZOS3;

                #if USE_FIB
                    fib.Rescale(result_width, result_height, resizer);
                #else
                    FIBITMAP newdib = FreeImage.Rescale(dib, result_width, result_height, resizer);
                    if (!newdib.IsNull)
                    {
                        FreeImage.Unload(dib);
                        dib.SetNull();
                        dib = newdib;
                    }
                #endif
              #elif USE_GDI
                    Bitmap resizedBitmap = Resize(bitmap, result_width, result_height);
                    bitmap.Dispose();
                    bitmap        = resizedBitmap;
                    resizedBitmap = null;
              #endif
                }


                // Check if the image must be converted to progressive jpeg
                if (ImageCache.Instance.use_progressive_jpeg && (result_width * result_height) >= ImageCache.Instance.progressive_jpeg_size_threshold)
                {
                    processed = true;

                    // Convert image to progressive jpeg

                    // FreeImage source code reveals that lower 7 bits of the FREE_IMAGE_SAVE_FLAGS enum are used for low-level quality control.
                    FREE_IMAGE_SAVE_FLAGS quality = (FREE_IMAGE_SAVE_FLAGS)ImageCache.Instance.progressive_jpeg_quality;
                    FREE_IMAGE_SAVE_FLAGS flags   = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | quality;

              #if USE_DIB || USE_FIB
                    stream.Dispose();
                    stream = new MemoryStream();

                #if USE_FIB
                    fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    fib.Dispose();
                #else
                    FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    FreeImage.Unload(dib);
                    dib.SetNull();
                #endif
              #else
                    FIBITMAP dib = FreeImage.CreateFromBitmap(bitmap);
                    bitmap.Dispose();
                    bitmap = null;
                    stream.Dispose();
                    stream = new MemoryStream();

                    FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    FreeImage.Unload(dib);
                    dib.SetNull();
              #endif
                }
                else
                if (processed)
                {
                    // image was rescaled, make new stream with rescaled bitmap

              #if USE_DIB || USE_FIB
                    FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_OPTIMIZE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL;

                    stream.Dispose();
                    stream = new MemoryStream();

                #if USE_FIB
                    fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    fib.Dispose();
                #else
                    FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags);
                    FreeImage.Unload(dib);
                    dib.SetNull();
                #endif
              #else
                    stream = GetBytesFromImage(bitmap);
              #endif
                    // For now, images that were resized because they exceeded the maximum dimensions are not saved to the cache.
                }

            #if USE_DIB
                FreeImage.Unload(dib);
                dib.SetNull();
            #elif USE_FIB
                fib.Dispose();
            #elif USE_GDI
                if (bitmap != null)
                {
                    bitmap.Dispose();
                    bitmap = null;
                }
            #endif

                // Always save thumbnails to the cache
                if (thumbnail)
                {
                    ImageCache.Instance.SaveToCache(filename, stream, true);
                }
                else
                if (processed)
                {
                    // Store rescaled and/or progressive jpegs in the cache for now.
                    string processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page);
                    ImageCache.Instance.SaveToCache(processed_filename, stream, false);
                }

                stream.Seek(0, SeekOrigin.Begin);
                return(response.FromStream(stream, MimeTypes.GetMimeType(".jpg")));
            }
        }
        // ================ Пробная программа - не используется ==================
        static void DocumentInputMain(string[] args)
        {
            string path = @"D:\Home\data\";

            Console.WriteLine("Start DocumentInput");
            //string fname = path + "WP_20170528_006.jpg";
            string fname  = path + "pharris1.tiff";
            Stream stream = File.OpenRead(fname);

            //ExifInfo(stream);

            using (var original = FreeImageBitmap.FromStream(stream))
            {
                Console.WriteLine($"Width={original.Width} Height={original.Height} ImageFormat={original.ImageFormat} {original.ToString()}");
                foreach (var m in original.Metadata)
                {
                    Console.WriteLine($"{m}");
                }
                int    x = original.Width, y = original.Height;
                double factor  = 150.0 / (x > y ? (double)x : (double)y);
                int    width   = (int)(factor * x);
                int    height  = (int)(factor * y);
                var    resized = new FreeImageBitmap(original, width, height);
                // JPEG_QUALITYGOOD is 75 JPEG.
                // JPEG_BASELINE strips metadata (EXIF, etc.)
                resized.Save(path + "out.jpg", FREE_IMAGE_FORMAT.FIF_JPEG,
                             FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD |
                             FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE);
            }
            //stream.Position = 0L;
            //Console.WriteLine($"ExifDate={ExifDate(stream)}");
            //Console.WriteLine($"ExifDate={ExifDate(fname)}");
            using (var image = new Bitmap(fname))
            {
                Console.WriteLine($"Width={image.Width} Height={image.Height}");
                foreach (var prop in image.PropertyItems)
                {
                    Console.WriteLine($"{prop.Id} {prop.Len} {prop.Type} {prop.Value} ");
                }
            }

            string text = "";

            // Используем пакет MesiaInfo.DotNetWrapper
            using (MediaInfo.DotNetWrapper.MediaInfo mediaInfo = new MediaInfo.DotNetWrapper.MediaInfo())
            {
                text += "\r\n\r\nOpen\r\n";
                mediaInfo.Open(fname);

                text += "\r\n\r\nInform with Complete=false\r\n";
                mediaInfo.Option("Complete");
                text += mediaInfo.Inform();

                text += "\r\n\r\nInform with Complete=true\r\n";
                mediaInfo.Option("Complete", "1");
                text += mediaInfo.Inform();

                text += "\r\n\r\nCustom Inform\r\n";
                mediaInfo.Option("Inform", "General;File size is %FileSize% bytes");
                text += mediaInfo.Inform();

                //foreach (string param in new[] { "BitRate", "BitRate/String", "BitRate_Mode" })
                //{
                //    text += "\r\n\r\nGet with Stream=Audio and Parameter='" + param + "'\r\n";
                //    text += mediaInfo.Get(StreamKind.Audio, 0, param);
                //}

                //text += "\r\n\r\nGet with Stream=General and Parameter=46\r\n";
                //text += mediaInfo.Get(StreamKind.General, 0, 46);

                //text += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n";
                //text += mediaInfo.CountGet(StreamKind.Audio);

                //text += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n";
                //text += mediaInfo.Get(StreamKind.General, 0, "AudioCount");

                //text += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n";
                //text += mediaInfo.Get(StreamKind.Audio, 0, "StreamCount");
            }

            Console.WriteLine(text);
        }