private BitmapEncoder CreateEncoder(Guid containerFormat) { var createdEncoder = BitmapEncoder.Create(containerFormat); if (!createdEncoder.CanEncode()) { createdEncoder = BitmapEncoder.Create(_settings.FallbackEncoder); } ConfigureEncoder(createdEncoder); return(createdEncoder); void ConfigureEncoder(BitmapEncoder encoder) { switch (encoder) { case JpegBitmapEncoder jpegEncoder: jpegEncoder.QualityLevel = MathHelpers.Clamp(_settings.JpegQualityLevel, 1, 100); break; case PngBitmapEncoder pngBitmapEncoder: pngBitmapEncoder.Interlace = _settings.PngInterlaceOption; break; case TiffBitmapEncoder tiffEncoder: tiffEncoder.Compression = _settings.TiffCompressOption; break; } } }
public static void GenerateImage(BitmapSource bitmap, ImageFormat format, Stream destStream) { BitmapEncoder encoder = BitmapEncoder.Create(format.Guid); encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(destStream); }
GetEncoder( BitmapSource bitmapSource ) { BitmapEncoder encoder = null; if (bitmapSource is BitmapFrame) { // // This code gets the encoder based on the decoder that was // used for this specific BitmapSource. // BitmapFrame bitmapImage = bitmapSource as BitmapFrame; BitmapCodecInfo codecInfo = null; if (bitmapImage != null && bitmapImage.Decoder != null) { codecInfo = bitmapImage.Decoder.CodecInfo; } if (codecInfo != null) { encoder = BitmapEncoder.Create(codecInfo.ContainerFormat); // Avoid GIF encoder which does not save transparency well if (!(encoder is JpegBitmapEncoder || encoder is PngBitmapEncoder || encoder is TiffBitmapEncoder || encoder is WmpBitmapEncoder) ) { encoder = null; } } } // // The code above assumes that the BitmapSource is actually // a BitmapImage. If it is not then we assume Png and use // that encoder. // if (encoder == null) { if (Microsoft.Internal.AlphaFlattener.Utility.NeedPremultiplyAlpha(bitmapSource)) { encoder = new WmpBitmapEncoder(); } else { encoder = new PngBitmapEncoder(); } } return(encoder); }
/// <summary> /// Add a image for the product /// </summary> /// <param name="id">the product id</param> /// <returns>action result</returns> public ActionResult AddNewProductImage(int id) { ProductItem CurrentProduct = ProductManager.GetProductByID(id); if (CurrentProduct == null) { return(Content(WebResult <string> .NormalErrorResult.ResponseString)); } HttpPostedFileBase file = Request.Files[0]; if (!file.ContentType.Contains("image") || file.ContentLength > 262144) { return(Content(WebResult <string> .FileTooLongResult.ResponseString)); } string mimetype = file.ContentType; string file_name = ProductManager.GenerateProductImageFileName(CurrentProduct.ProductID, ProductManager.FromMimeTypeGetExtendName(mimetype)); BitmapDecoder decoder = BitmapDecoder.Create(file.InputStream, BitmapCreateOptions.None, BitmapCacheOption.Default); /* 生成小图标 */ TransformedBitmap thumb_img = new TransformedBitmap(decoder.Frames[0], new System.Windows.Media.ScaleTransform(0.2, 0.2)); BitmapEncoder encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); using (FileStream thumb_file = new FileStream(HttpContext.Server.MapPath("~/images/product/thumb/" + file_name), FileMode.Create)) { encoder.Frames.Add(BitmapFrame.Create(thumb_img)); encoder.Save(thumb_file); } file.SaveAs(HttpContext.Server.MapPath("~/Images/product/normal/" + file_name)); ProductImageItem item = new ProductImageItem(); item.ProductID = CurrentProduct.ProductID; item.ImageUrl = file_name; item.MimeType = file.ContentType; item.Description = ""; //the first image is default to logo. if (file_name.Contains("_0.")) { item.ForLogo = true; } if (ProductManager.AddNewImageToProduct(item)) { return(Content(WebResult <string> .SuccessResult.ResponseString)); } else { return(Content(WebResult <string> .NormalErrorResult.ResponseString)); } }
private static string ToBase64(BitmapDecoder decoder) { BitmapEncoder encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); foreach (BitmapFrame frame in decoder.Frames) { encoder.Frames.Add(frame); } using (MemoryStream stream = new MemoryStream()) { encoder.Save(stream); return(Convert.ToBase64String(stream.ToArray(), Base64FormattingOptions.InsertLineBreaks)); } }
private static async Task <Photo.Metadata> reloadAndSave( Photo photo, bool forceJpeg, string destFile) { using (var mmap = MemoryMappedFile.OpenExisting( mmapName(photo.FileName), MemoryMappedFileRights.Read)) { using (var stream = new UnsafeMemoryMapStream( mmap.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read), FileAccess.Read)) { (var sourceFrame, var format) = loadFrame(stream.Stream); var md = sourceFrame.Metadata.Clone() as BitmapMetadata; Photo.Metadata newMetadata = await Exif.SetMetadata(photo, md); newMetadata.Width = sourceFrame.PixelWidth; newMetadata.Height = sourceFrame.PixelHeight; BitmapEncoder encoder = forceJpeg ? new JpegBitmapEncoder() : BitmapEncoder.Create(format); encoder.Frames.Add( BitmapFrame.Create( sourceFrame, null, md, sourceFrame.ColorContexts)); if (encoder is JpegBitmapEncoder jpg) { jpg.Rotation = Exif.SaveRotation(md); } sourceFrame = null; using (var outFile = new FileStream(destFile, FileMode.CreateNew)) { encoder.Save(outFile); } return(newMetadata); } } }
public void Execute() { string path; using (var inputStream = File.OpenRead(_file)) { var decoder = BitmapDecoder.Create( inputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); if (!encoder.CanEncode()) { encoder = BitmapEncoder.Create(_settings.FallbackEncoder); } ConfigureEncoder(encoder); if (decoder.Metadata != null) { try { encoder.Metadata = decoder.Metadata; } catch (InvalidOperationException) { } } if (decoder.Palette != null) { encoder.Palette = decoder.Palette; } foreach (var originalFrame in decoder.Frames) { encoder.Frames.Add( BitmapFrame.Create( Transform(originalFrame), /*thumbnail:*/ null, (BitmapMetadata)originalFrame.Metadata, colorContexts: null)); } path = GetDestinationPath(encoder); using (var outputStream = File.Open(path, FileMode.CreateNew, FileAccess.Write)) encoder.Save(outputStream); } if (_settings.KeepDateModified) { File.SetLastWriteTimeUtc(path, File.GetLastWriteTimeUtc(_file)); } if (_settings.Replace) { var backup = GetBackupPath(); File.Replace(path, _file, backup, ignoreMetadataErrors: true); var shell = (IShellDispatch)Activator.CreateInstance( Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000"), throwOnError: true)); var recycleBin = shell.NameSpace(ShellSpecialFolderConstants.ssfBITBUCKET); recycleBin.MoveHere(backup); } }
public void Execute() { string path; using (var inputStream = File.OpenRead(_file)) { var decoder = BitmapDecoder.Create( inputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); if (!encoder.CanEncode()) { encoder = BitmapEncoder.Create(_settings.FallbackEncoder); } ConfigureEncoder(encoder); if (decoder.Metadata != null) { try { encoder.Metadata = decoder.Metadata; } catch (InvalidOperationException) { } } if (decoder.Palette != null) { encoder.Palette = decoder.Palette; } foreach (var originalFrame in decoder.Frames) { BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata; if (metadata != null) { try { // Detect whether metadata can copied successfully _ = metadata.Clone(); } catch (ArgumentException) { metadata = null; } } encoder.Frames.Add( BitmapFrame.Create( Transform(originalFrame), thumbnail: null, metadata, // TODO: Add an option to strip any metadata that doesn't affect rendering (issue #3) colorContexts: null)); } path = GetDestinationPath(encoder); Directory.CreateDirectory(Path.GetDirectoryName(path)); using (var outputStream = File.Open(path, FileMode.CreateNew, FileAccess.Write)) { encoder.Save(outputStream); } } if (_settings.KeepDateModified) { File.SetLastWriteTimeUtc(path, File.GetLastWriteTimeUtc(_file)); } if (_settings.Replace) { var backup = GetBackupPath(); File.Replace(path, _file, backup, ignoreMetadataErrors: true); FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } }
public void Execute() { string path; using (var inputStream = _fileSystem.File.OpenRead(_file)) { var decoder = BitmapDecoder.Create( inputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); if (!encoder.CanEncode()) { encoder = BitmapEncoder.Create(_settings.FallbackEncoder); } ConfigureEncoder(encoder); if (decoder.Metadata != null) { try { encoder.Metadata = decoder.Metadata; } catch (InvalidOperationException) { } } if (decoder.Palette != null) { encoder.Palette = decoder.Palette; } foreach (var originalFrame in decoder.Frames) { BitmapMetadata metadata = (BitmapMetadata)originalFrame.Metadata; if (metadata != null) { try { #if DEBUG Debug.WriteLine($"### Processing metadata of file {_file}"); metadata.PrintsAllMetadataToDebugOutput(); #endif // read all metadata and build up metadata object from the scratch. Discard invalid (unreadable/unwritable) metadata. var newMetadata = new BitmapMetadata(metadata.Format); var listOfMetadata = metadata.GetListOfMetadata(); foreach (var(metadataPath, value) in listOfMetadata) { if (value is BitmapMetadata bitmapMetadata) { var innerMetadata = new BitmapMetadata(bitmapMetadata.Format); newMetadata.SetQuerySafe(metadataPath, innerMetadata); } else { newMetadata.SetQuerySafe(metadataPath, value); } } if (newMetadata.IsMetadataObjectValid()) { metadata = newMetadata; } else { // Seems like we build an invalid metadata object. ImageResizer will fail when trying to write the image to disk. We discard all metadata to be able to save the image. metadata = null; } } catch (ArgumentException ex) { metadata = null; Debug.WriteLine(ex); } } if (_settings.RemoveMetadata && metadata != null) { // strip any metadata that doesn't affect rendering var newMetadata = new BitmapMetadata(metadata.Format); metadata.CopyMetadataPropertyTo(newMetadata, "System.Photo.Orientation"); metadata.CopyMetadataPropertyTo(newMetadata, "System.Image.ColorSpace"); metadata = newMetadata; } encoder.Frames.Add( BitmapFrame.Create( Transform(originalFrame), thumbnail: null, /* should be null, see #15413 */ metadata, colorContexts: null /* should be null, see #14866 */)); } path = GetDestinationPath(encoder); _fileSystem.Directory.CreateDirectory(_fileSystem.Path.GetDirectoryName(path)); using (var outputStream = _fileSystem.File.Open(path, FileMode.CreateNew, FileAccess.Write)) { encoder.Save(outputStream); } } if (_settings.KeepDateModified) { _fileSystem.File.SetLastWriteTimeUtc(path, _fileSystem.File.GetLastWriteTimeUtc(_file)); } if (_settings.Replace) { var backup = GetBackupPath(); _fileSystem.File.Replace(path, _file, backup, ignoreMetadataErrors: true); FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } }
public void Execute() { string path; using (var inputStream = File.OpenRead(_file)) { var decoder = BitmapDecoder.Create( inputStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); if (!encoder.CanEncode()) { encoder = BitmapEncoder.Create(_settings.FallbackEncoder); } ConfigureEncoder(encoder); if (decoder.Metadata != null) { try { encoder.Metadata = decoder.Metadata; } catch (InvalidOperationException) { } } if (decoder.Palette != null) { encoder.Palette = decoder.Palette; } foreach (var originalFrame in decoder.Frames) { encoder.Frames.Add( BitmapFrame.Create( Transform(originalFrame), /*thumbnail:*/ null, (BitmapMetadata)originalFrame.Metadata, colorContexts: null)); } path = GetDestinationPath(encoder); using (var outputStream = File.Open(path, FileMode.CreateNew, FileAccess.Write)) encoder.Save(outputStream); } if (_settings.KeepDateModified) { File.SetLastWriteTimeUtc(path, File.GetLastWriteTimeUtc(_file)); } if (_settings.Replace) { var backup = GetBackupPath(); File.Replace(path, _file, backup, ignoreMetadataErrors: true); FileSystem.DeleteFile(backup, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } }
ConvertTo( ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType ) { string bitmapName = "bitmap" + m_bitmapId; BitmapEncoder encoder = null; m_bitmapId++; BitmapFrame bmpd = value as BitmapFrame; if (bmpd != null) { BitmapCodecInfo codec = null; if (bmpd.Decoder != null) { codec = bmpd.Decoder.CodecInfo; } if (codec != null) { encoder = BitmapEncoder.Create(codec.ContainerFormat); string extension = ""; if (encoder is BmpBitmapEncoder) { extension = "bmp"; } else if (encoder is JpegBitmapEncoder) { extension = "jpg"; } else if (encoder is PngBitmapEncoder) { extension = "png"; } else if (encoder is TiffBitmapEncoder) { extension = "tif"; } else { encoder = null; } if (encoder != null) { bitmapName = bitmapName + '.' + extension; } } } if (encoder == null) { if (Microsoft.Internal.AlphaFlattener.Utility.NeedPremultiplyAlpha(value as BitmapSource)) { encoder = new WmpBitmapEncoder(); bitmapName = bitmapName + ".wmp"; } else { encoder = new PngBitmapEncoder(); bitmapName = bitmapName + ".png"; } } if (value is BitmapFrame) { encoder.Frames.Add((BitmapFrame)value); } else { encoder.Frames.Add(BitmapFrame.Create((BitmapSource)value)); } int index = m_mainFile.LastIndexOf('.'); if (index < 0) { index = m_mainFile.Length; } string uri = m_mainFile.Substring(0, index) + "_" + bitmapName; Stream bitmapStreamDest = new System.IO.FileStream(uri, FileMode.Create, FileAccess.ReadWrite, FileShare.None); #if DEBUG Console.WriteLine("Saving " + uri); #endif encoder.Save(bitmapStreamDest); bitmapStreamDest.Close(); return(new Uri(BaseUriHelper.SiteOfOriginBaseUri, uri)); }
public string Resize(string sourcePath) { Debug.Assert(!String.IsNullOrWhiteSpace(sourcePath)); FileInfo metaInfo = new FileInfo(sourcePath); var encoderDefaulted = false; BitmapDecoder decoder; using (var sourceStream = File.OpenRead(sourcePath)) { // NOTE: Using BitmapCacheOption.OnLoad here will read the entire file into // memory which allows us to dispose of the file stream immediately decoder = BitmapDecoder.Create(sourceStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } var encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); try { // NOTE: This will throw if the codec dose not support encoding var _ = encoder.CodecInfo; } catch (NotSupportedException) { // Fallback to JPEG encoder encoder = (BitmapEncoder)Activator.CreateInstance(DefaultEncoderType); encoderDefaulted = true; } // TODO: Copy container-level metadata if codec supports it SetEncoderSettings(encoder); string destinationPath = null; // NOTE: Only TIFF and GIF images support multiple frames foreach (var sourceFrame in decoder.Frames) { // Apply the transform var transform = GetTransform(sourceFrame); var transformedBitmap = new TransformedBitmap(sourceFrame, transform); // TODO: Optionally copy metadata // Create the destination frame var thumbnail = sourceFrame.Thumbnail; var metadata = sourceFrame.Metadata as BitmapMetadata; var colorContexts = sourceFrame.ColorContexts; var destinationFrame = BitmapFrame.Create(transformedBitmap, thumbnail, metadata, colorContexts); encoder.Frames.Add(destinationFrame); // Set the destination path using the first frame if (destinationPath == null) { if (encoderDefaulted) { sourcePath = Path.ChangeExtension(sourcePath, DefaultEncoderExtension); } destinationPath = _renamer.Rename(sourcePath); } } var fileExists = File.Exists(destinationPath); var finalPath = destinationPath; if (fileExists) { destinationPath = Path.GetTempFileName(); } using (var destinationStream = File.OpenWrite(destinationPath)) { // Save the final image encoder.Save(destinationStream); } // Change metadata if (_keepMetadata) { FileInfo newInfo = new FileInfo(destinationPath); newInfo.Attributes = metaInfo.Attributes; newInfo.CreationTime = metaInfo.CreationTime; newInfo.CreationTimeUtc = metaInfo.CreationTimeUtc; newInfo.IsReadOnly = metaInfo.IsReadOnly; newInfo.LastAccessTime = metaInfo.LastAccessTime; newInfo.LastAccessTimeUtc = metaInfo.LastAccessTimeUtc; newInfo.LastWriteTime = metaInfo.LastWriteTime; newInfo.LastWriteTimeUtc = metaInfo.LastWriteTimeUtc; } // Move any existing file to the Recycle Bin if (fileExists) { // TODO: Is there a better way to do this without a reference to Microsoft.VisualBasic? FileSystem.DeleteFile(finalPath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); File.Move(destinationPath, finalPath); } Debug.Assert(!String.IsNullOrWhiteSpace(finalPath)); return(finalPath); }
private void Resize(string sourcePath, BitmapEncoder overrideEncoder = null) { Contract.Requires(!String.IsNullOrWhiteSpace(sourcePath)); Contract.Ensures(!String.IsNullOrWhiteSpace(Contract.Result <string>())); //string extension = Path.GetExtension(sourcePath).ToUpperInvariant(); string destinationPath = sourcePath; switch (_processingCmd.ActionToPerform) { case ManipulateAction.CopyAsThumbnail: _processingCmd.CreateNewFile = true; _processingCmd.PostFixFile = "_thumb"; break; } if (_processingCmd.CreateNewFile) { destinationPath = FileUtil.GenerateNewFileName(sourcePath, _processingCmd.PostFixFile); } BitmapDecoder decoder; BitmapEncoder encoder; using (var sourceStream = File.OpenRead(sourcePath)) { // NOTE: Using BitmapCacheOption.OnLoad here will read the entire file into // memory which allows us to dispose of the file stream immediately decoder = BitmapDecoder.Create(sourceStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } //See if a destination file type is specified if (overrideEncoder == null) { encoder = BitmapEncoder.Create(decoder.CodecInfo.ContainerFormat); try { // NOTE: This will throw if the codec dose not support encoding var _ = encoder.CodecInfo; } catch (NotSupportedException) { // Fallback to JPEG encoder encoder = CreateEncoder(DefaultJpegEncoderType); } } else { encoder = overrideEncoder; } // TODO: Copy container-level metadata if codec supports it SetEncoderSettings(encoder); // NOTE: Only TIFF and GIF images support multiple frames foreach (var sourceFrame in decoder.Frames) { // Apply the transform var transform = GetTransform(sourceFrame); var transformedBitmap = new TransformedBitmap(sourceFrame, transform); // TODO: Optionally copy metadata // Create the destination frame var thumbnail = sourceFrame.Thumbnail; var metadata = sourceFrame.Metadata as BitmapMetadata; var colorContexts = sourceFrame.ColorContexts; var destinationFrame = BitmapFrame.Create(transformedBitmap, thumbnail, metadata, colorContexts); encoder.Frames.Add(destinationFrame); } var fileExists = File.Exists(destinationPath); var finalPath = destinationPath; var result = new ResizeResult(finalPath, FileUtil.CreateActionMessage(finalPath, _processingCmd)); result.SourceFileName = sourcePath; result.SizeBefore = new FileInfo(sourcePath).Length; if (fileExists) { destinationPath = Path.GetTempFileName(); } using (var destinationStream = File.OpenWrite(destinationPath)) { // Save the final image encoder.Save(destinationStream); } // Move any existing file to the Recycle Bin if (fileExists) { OnBeforeWritingFile(result); // TODO: Is there a better way to do this without a reference to Microsoft.VisualBasic? //FileSystem.DeleteFile(finalPath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); File.Delete(finalPath); File.Move(destinationPath, finalPath); } result.SizeAfter = new FileInfo(finalPath).Length; result.PercentSaved = result.SizeBefore > 0 ? Math.Round((result.SizeBefore - result.SizeAfter) / result.SizeBefore * 100, 2) : 0; OnProgress(new ResizerEventArgs(result)); }