Added the SurfaceOutputSettings to the IFileFormatHandler, changed the TryLoad to LoadDrawablesFromStream to enable returning multiple values.

This commit is contained in:
Robin Krom 2022-02-16 21:21:24 +01:00
commit 52c042572f
No known key found for this signature in database
GPG key ID: BCC01364F1371490
15 changed files with 108 additions and 261 deletions

View file

@ -303,11 +303,11 @@ EndSelection:<<<<<<<4
} }
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>(); var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>();
var supportedExtensions = fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadDrawableFromStream).ToList(); var supportedExtensions = fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadDrawableFromStream).ToList();
foreach (var fileData in IterateClipboardContent(dataObject)) foreach (var (stream, filename) in IterateClipboardContent(dataObject))
{ {
try try
{ {
var extension = Path.GetExtension(fileData.filename)?.ToLowerInvariant(); var extension = Path.GetExtension(filename)?.ToLowerInvariant();
if (supportedExtensions.Contains(extension)) if (supportedExtensions.Contains(extension))
{ {
return true; return true;
@ -319,7 +319,7 @@ EndSelection:<<<<<<<4
} }
finally finally
{ {
fileData.stream?.Dispose(); stream?.Dispose();
} }
} }
@ -609,15 +609,10 @@ EndSelection:<<<<<<<4
continue; continue;
} }
IDrawableContainer drawableContainer = null; IEnumerable<IDrawableContainer> drawableContainers;
try try
{ {
if (!fileFormatHandlers.TryLoadDrawableFromStream(fileData.stream, extension, out drawableContainer)) drawableContainers = fileFormatHandlers.LoadDrawablesFromStream(fileData.stream, extension);
{
continue;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -629,7 +624,10 @@ EndSelection:<<<<<<<4
fileData.stream?.Dispose(); fileData.stream?.Dispose();
} }
// If we get here, there is an image // If we get here, there is an image
yield return drawableContainer; foreach (var container in drawableContainers)
{
yield return container;
}
} }
// check if files are supplied // check if files are supplied
@ -643,12 +641,10 @@ EndSelection:<<<<<<<4
IDrawableContainer drawableContainer = null; IDrawableContainer drawableContainer = null;
using FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read); using FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);
IEnumerable<IDrawableContainer> drawableContainers;
try try
{ {
if (!fileFormatHandlers.TryLoadDrawableFromStream(fileStream, extension, out drawableContainer)) drawableContainers = fileFormatHandlers.LoadDrawablesFromStream(fileStream, extension);
{
continue;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -656,7 +652,10 @@ EndSelection:<<<<<<<4
continue; continue;
} }
// If we get here, there is an image // If we get here, there is an image
yield return drawableContainer; foreach (var container in drawableContainers)
{
yield return container;
}
} }
} }
@ -884,11 +883,7 @@ EndSelection:<<<<<<<4
// From here, imageStream is a valid stream // From here, imageStream is a valid stream
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>(); var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>();
if (!fileFormatHandlers.TryLoadDrawableFromStream(imageStream, format, out drawableContainer)) return fileFormatHandlers.LoadDrawablesFromStream(imageStream, format).FirstOrDefault();
{
return drawableContainer;
}
return null;
} }
/// <summary> /// <summary>

View file

@ -25,6 +25,7 @@ using System.IO;
using System.Linq; using System.Linq;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Drawing; using Greenshot.Base.Interfaces.Drawing;
using Greenshot.Base.Interfaces.Plugin;
namespace Greenshot.Base.Core.FileFormatHandlers namespace Greenshot.Base.Core.FileFormatHandlers
{ {
@ -84,7 +85,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers
/// <param name="extension">string</param> /// <param name="extension">string</param>
/// <param name="surface">ISurface</param> /// <param name="surface">ISurface</param>
/// <returns>bool</returns> /// <returns>bool</returns>
public static bool TrySaveToStream(this IEnumerable<IFileFormatHandler> fileFormatHandlers, Bitmap bitmap, Stream destination, string extension, ISurface surface = null) public static bool TrySaveToStream(this IEnumerable<IFileFormatHandler> fileFormatHandlers, Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
extension = NormalizeExtension(extension); extension = NormalizeExtension(extension);
@ -114,10 +115,9 @@ namespace Greenshot.Base.Core.FileFormatHandlers
/// <param name="fileFormatHandlers">IEnumerable{IFileFormatHandler}</param> /// <param name="fileFormatHandlers">IEnumerable{IFileFormatHandler}</param>
/// <param name="stream">Stream</param> /// <param name="stream">Stream</param>
/// <param name="extension">string</param> /// <param name="extension">string</param>
/// <param name="drawableContainer">IDrawableContainer out</param>
/// <param name="parentSurface">ISurface</param> /// <param name="parentSurface">ISurface</param>
/// <returns>bool true if it was successful</returns> /// <returns>IEnumerable{IDrawableContainer}</returns>
public static bool TryLoadDrawableFromStream(this IEnumerable<IFileFormatHandler> fileFormatHandlers, Stream stream, string extension, out IDrawableContainer drawableContainer, ISurface parentSurface = null) public static IEnumerable<IDrawableContainer> LoadDrawablesFromStream(this IEnumerable<IFileFormatHandler> fileFormatHandlers, Stream stream, string extension, ISurface parentSurface = null)
{ {
extension = NormalizeExtension(extension); extension = NormalizeExtension(extension);
@ -126,13 +126,12 @@ namespace Greenshot.Base.Core.FileFormatHandlers
.OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadDrawableFromStream, extension)) .OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadDrawableFromStream, extension))
.FirstOrDefault(); .FirstOrDefault();
if (loadfileFormatHandler == null) if (loadfileFormatHandler != null)
{ {
drawableContainer = null; return loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface);
return false;
} }
return loadfileFormatHandler.TryLoadDrawableFromStream(stream, extension, out drawableContainer, parentSurface); return Enumerable.Empty<IDrawableContainer>();
} }
/// <summary> /// <summary>

View file

@ -20,8 +20,6 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Imaging; using System.Drawing.Imaging;
@ -124,7 +122,7 @@ namespace Greenshot.Base.Core
try try
{ {
// Check if we want to use a memory stream, to prevent issues with non seakable streams // Check if we want to use a memory stream, to prevent issues with non seekable streams
// The save is made to the targetStream, this is directed to either the MemoryStream or the original // The save is made to the targetStream, this is directed to either the MemoryStream or the original
Stream targetStream = stream; Stream targetStream = stream;
if (!stream.CanSeek) if (!stream.CanSeek)
@ -136,7 +134,7 @@ namespace Greenshot.Base.Core
} }
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>(); var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>();
if (!fileFormatHandlers.TrySaveToStream(imageToSave as Bitmap, targetStream, outputSettings.Format.ToString(), surface)) if (!fileFormatHandlers.TrySaveToStream(imageToSave as Bitmap, targetStream, outputSettings.Format.ToString(), surface, outputSettings))
{ {
return; return;
} }
@ -153,89 +151,6 @@ namespace Greenshot.Base.Core
} }
} }
/// <summary>
/// Write the passed Image to a tmp-file and call an external process, than read the file back and write it to the targetStream
/// </summary>
/// <param name="imageToProcess">Image to pass to the external process</param>
/// <param name="targetStream">stream to write the processed image to</param>
/// <returns></returns>
private static bool ProcessPngImageExternally(Image imageToProcess, Stream targetStream)
{
if (string.IsNullOrEmpty(CoreConfig.OptimizePNGCommand))
{
return false;
}
if (!File.Exists(CoreConfig.OptimizePNGCommand))
{
Log.WarnFormat("Can't find 'OptimizePNGCommand' {0}", CoreConfig.OptimizePNGCommand);
return false;
}
string tmpFileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".png");
try
{
using (FileStream tmpStream = File.Create(tmpFileName))
{
Log.DebugFormat("Writing png to tmp file: {0}", tmpFileName);
imageToProcess.Save(tmpStream, ImageFormat.Png);
if (Log.IsDebugEnabled)
{
Log.DebugFormat("File size before processing {0}", new FileInfo(tmpFileName).Length);
}
}
if (Log.IsDebugEnabled)
{
Log.DebugFormat("Starting : {0}", CoreConfig.OptimizePNGCommand);
}
ProcessStartInfo processStartInfo = new ProcessStartInfo(CoreConfig.OptimizePNGCommand)
{
Arguments = string.Format(CoreConfig.OptimizePNGCommandArguments, tmpFileName),
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
using Process process = Process.Start(processStartInfo);
if (process != null)
{
process.WaitForExit();
if (process.ExitCode == 0)
{
if (Log.IsDebugEnabled)
{
Log.DebugFormat("File size after processing {0}", new FileInfo(tmpFileName).Length);
Log.DebugFormat("Reading back tmp file: {0}", tmpFileName);
}
byte[] processedImage = File.ReadAllBytes(tmpFileName);
targetStream.Write(processedImage, 0, processedImage.Length);
return true;
}
Log.ErrorFormat("Error while processing PNG image: {0}", process.ExitCode);
Log.ErrorFormat("Output: {0}", process.StandardOutput.ReadToEnd());
Log.ErrorFormat("Error: {0}", process.StandardError.ReadToEnd());
}
}
catch (Exception e)
{
Log.Error("Error while processing PNG image: ", e);
}
finally
{
if (File.Exists(tmpFileName))
{
Log.DebugFormat("Cleaning up tmp file: {0}", tmpFileName);
File.Delete(tmpFileName);
}
}
return false;
}
/// <summary> /// <summary>
/// Create an image from a surface with the settings from the output settings applied /// Create an image from a surface with the settings from the output settings applied
/// </summary> /// </summary>
@ -607,93 +522,5 @@ namespace Greenshot.Base.Core
File.Delete(path); File.Delete(path);
} }
} }
/// <summary>
/// Write the images to the stream as icon
/// Every image is resized to 256x256 (but the content maintains the aspect ratio)
/// </summary>
/// <param name="stream">Stream to write to</param>
/// <param name="images">List of images</param>
public static void WriteIcon(Stream stream, IList<Image> images)
{
var binaryWriter = new BinaryWriter(stream);
//
// ICONDIR structure
//
binaryWriter.Write((short) 0); // reserved
binaryWriter.Write((short) 1); // image type (icon)
binaryWriter.Write((short) images.Count); // number of images
IList<Size> imageSizes = new List<Size>();
IList<MemoryStream> encodedImages = new List<MemoryStream>();
foreach (var image in images)
{
// Pick the best fit
var sizes = new[]
{
16, 32, 48
};
int size = 256;
foreach (var possibleSize in sizes)
{
if (image.Width <= possibleSize && image.Height <= possibleSize)
{
size = possibleSize;
break;
}
}
var imageStream = new MemoryStream();
if (image.Width == size && image.Height == size)
{
using var clonedImage = ImageHelper.Clone(image, PixelFormat.Format32bppArgb);
clonedImage.Save(imageStream, ImageFormat.Png);
imageSizes.Add(new Size(size, size));
}
else
{
// Resize to the specified size, first make sure the image is 32bpp
using var clonedImage = ImageHelper.Clone(image, PixelFormat.Format32bppArgb);
using var resizedImage = ImageHelper.ResizeImage(clonedImage, true, true, Color.Empty, size, size, null);
resizedImage.Save(imageStream, ImageFormat.Png);
imageSizes.Add(resizedImage.Size);
}
imageStream.Seek(0, SeekOrigin.Begin);
encodedImages.Add(imageStream);
}
//
// ICONDIRENTRY structure
//
const int iconDirSize = 6;
const int iconDirEntrySize = 16;
var offset = iconDirSize + (images.Count * iconDirEntrySize);
for (int i = 0; i < images.Count; i++)
{
var imageSize = imageSizes[i];
// Write the width / height, 0 means 256
binaryWriter.Write(imageSize.Width == 256 ? (byte) 0 : (byte) imageSize.Width);
binaryWriter.Write(imageSize.Height == 256 ? (byte) 0 : (byte) imageSize.Height);
binaryWriter.Write((byte) 0); // no pallete
binaryWriter.Write((byte) 0); // reserved
binaryWriter.Write((short) 0); // no color planes
binaryWriter.Write((short) 32); // 32 bpp
binaryWriter.Write((int) encodedImages[i].Length); // image data length
binaryWriter.Write(offset);
offset += (int) encodedImages[i].Length;
}
binaryWriter.Flush();
//
// Write image data
//
foreach (var encodedImage in encodedImages)
{
encodedImage.WriteTo(stream);
encodedImage.Dispose();
}
}
} }
} }

View file

@ -106,7 +106,9 @@ namespace Greenshot.Base.Core
using var memoryStream = GetAsMemoryStream(url); using var memoryStream = GetAsMemoryStream(url);
try try
{ {
if (fileFormatHandlers.TryLoadDrawableFromStream(memoryStream, match.Success ? match.Groups["extension"]?.Value : null, out var drawableContainer)) var extension = match.Success ? match.Groups["extension"]?.Value : null;
var drawableContainer = fileFormatHandlers.LoadDrawablesFromStream(memoryStream, extension).FirstOrDefault();
if (drawableContainer != null)
{ {
return drawableContainer; return drawableContainer;
} }
@ -132,7 +134,10 @@ namespace Greenshot.Base.Core
} }
using var memoryStream2 = GetAsMemoryStream(match.Value); using var memoryStream2 = GetAsMemoryStream(match.Value);
if (fileFormatHandlers.TryLoadDrawableFromStream(memoryStream2, match.Success ? match.Groups["extension"]?.Value : null, out var drawableContainer))
var extension = match.Success ? match.Groups["extension"]?.Value : null;
var drawableContainer = fileFormatHandlers.LoadDrawablesFromStream(memoryStream2, extension).FirstOrDefault();
if (drawableContainer != null)
{ {
return drawableContainer; return drawableContainer;
} }

View file

@ -23,6 +23,7 @@ using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using Greenshot.Base.Interfaces.Drawing; using Greenshot.Base.Interfaces.Drawing;
using Greenshot.Base.Interfaces.Plugin;
namespace Greenshot.Base.Interfaces namespace Greenshot.Base.Interfaces
{ {
@ -44,7 +45,7 @@ namespace Greenshot.Base.Interfaces
/// <summary> /// <summary>
/// Registry for all the extensions this IFileFormatHandler support /// Registry for all the extensions this IFileFormatHandler support
/// </summary> /// </summary>
IDictionary<FileFormatHandlerActions, IList<string>> SupportedExtensions { get; } IDictionary<FileFormatHandlerActions, IReadOnlyCollection<string>> SupportedExtensions { get; }
/// <summary> /// <summary>
/// Priority (from high int.MinValue, low int.MaxValue) of this IFileFormatHandler for the specified action and extension /// Priority (from high int.MinValue, low int.MaxValue) of this IFileFormatHandler for the specified action and extension
@ -62,8 +63,9 @@ namespace Greenshot.Base.Interfaces
/// <param name="destination">Stream</param> /// <param name="destination">Stream</param>
/// <param name="extension">extension</param> /// <param name="extension">extension</param>
/// <param name="surface">ISurface with the elements for those file types which can store a surface (.greenshot)</param> /// <param name="surface">ISurface with the elements for those file types which can store a surface (.greenshot)</param>
/// <param name="surfaceOutputSettings">SurfaceOutputSettings</param>
/// <returns>bool true if it was successful</returns> /// <returns>bool true if it was successful</returns>
public bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null); public bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null);
/// <summary> /// <summary>
/// ///
@ -79,9 +81,8 @@ namespace Greenshot.Base.Interfaces
/// </summary> /// </summary>
/// <param name="stream">Stream</param> /// <param name="stream">Stream</param>
/// <param name="extension">string</param> /// <param name="extension">string</param>
/// <param name="drawableContainer">IDrawableContainer out</param>
/// <param name="parentSurface">ISurface</param> /// <param name="parentSurface">ISurface</param>
/// <returns>bool true if it was successful</returns> /// <returns>IEnumerable{IDrawableContainer}</returns>
public bool TryLoadDrawableFromStream(Stream stream, string extension, out IDrawableContainer drawableContainer, ISurface parentSurface = null); public IEnumerable<IDrawableContainer> LoadDrawablesFromStream(Stream stream, string extension, ISurface parentSurface = null);
} }
} }

View file

@ -1,4 +1,25 @@
using System.Collections.Generic; /*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: https://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.Core.Enums; using Greenshot.Base.Core.Enums;
using Greenshot.Base.Effects; using Greenshot.Base.Effects;

View file

@ -24,6 +24,7 @@ using System.Drawing;
using System.IO; using System.IO;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Drawing; using Greenshot.Base.Interfaces.Drawing;
using Greenshot.Base.Interfaces.Plugin;
using Greenshot.Editor.Drawing; using Greenshot.Editor.Drawing;
namespace Greenshot.Editor.FileFormatHandlers namespace Greenshot.Editor.FileFormatHandlers
@ -31,7 +32,7 @@ namespace Greenshot.Editor.FileFormatHandlers
public abstract class AbstractFileFormatHandler : IFileFormatHandler public abstract class AbstractFileFormatHandler : IFileFormatHandler
{ {
/// <inheritdoc /> /// <inheritdoc />
public IDictionary<FileFormatHandlerActions, IList<string>> SupportedExtensions { get; } = new Dictionary<FileFormatHandlerActions, IList<string>>(); public IDictionary<FileFormatHandlerActions, IReadOnlyCollection<string>> SupportedExtensions { get; } = new Dictionary<FileFormatHandlerActions, IReadOnlyCollection<string>>();
/// <inheritdoc /> /// <inheritdoc />
public virtual int PriorityFor(FileFormatHandlerActions fileFormatHandlerAction, string extension) public virtual int PriorityFor(FileFormatHandlerActions fileFormatHandlerAction, string extension)
@ -39,7 +40,7 @@ namespace Greenshot.Editor.FileFormatHandlers
return 0; return 0;
} }
public abstract bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null); public abstract bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null);
public abstract bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap); public abstract bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap);
@ -48,23 +49,18 @@ namespace Greenshot.Editor.FileFormatHandlers
/// </summary> /// </summary>
/// <param name="stream">Stream</param> /// <param name="stream">Stream</param>
/// <param name="extension">string</param> /// <param name="extension">string</param>
/// <param name="drawableContainer">IDrawableContainer out</param> /// <param name="parent">ISurface</param>
/// <param name="parentSurface">ISurface</param> /// <returns>IEnumerable{IDrawableContainer}</returns>
/// <returns>bool</returns> public virtual IEnumerable<IDrawableContainer> LoadDrawablesFromStream(Stream stream, string extension, ISurface parent = null)
public virtual bool TryLoadDrawableFromStream(Stream stream, string extension, out IDrawableContainer drawableContainer, ISurface parentSurface = null)
{ {
if (TryLoadFromStream(stream, extension, out var bitmap)) if (TryLoadFromStream(stream, extension, out var bitmap))
{ {
var imageContainer = new ImageContainer(parentSurface) var imageContainer = new ImageContainer(parent)
{ {
Image = bitmap Image = bitmap
}; };
drawableContainer = imageContainer; yield return imageContainer;
return true;
} }
drawableContainer = null;
return true;
} }
} }
} }

View file

@ -28,6 +28,7 @@ using System.Linq;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.IniFile; using Greenshot.Base.IniFile;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Plugin;
using log4net; using log4net;
namespace Greenshot.Editor.FileFormatHandlers namespace Greenshot.Editor.FileFormatHandlers
@ -38,7 +39,7 @@ namespace Greenshot.Editor.FileFormatHandlers
public class DefaultFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler public class DefaultFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(DefaultFileFormatHandler)); private static readonly ILog Log = LogManager.GetLogger(typeof(DefaultFileFormatHandler));
private readonly List<string> _ourExtensions = new() { ".png", ".bmp", ".gif", ".jpg", ".jpeg", ".tiff", ".tif" }; private readonly IReadOnlyCollection<string> _ourExtensions = new[] { ".png", ".bmp", ".gif", ".jpg", ".jpeg", ".tiff", ".tif" };
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
public DefaultFileFormatHandler() public DefaultFileFormatHandler()
{ {
@ -48,7 +49,7 @@ namespace Greenshot.Editor.FileFormatHandlers
} }
/// <inheritdoc /> /// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
ImageFormat imageFormat = extension switch ImageFormat imageFormat = extension switch
{ {
@ -66,7 +67,7 @@ namespace Greenshot.Editor.FileFormatHandlers
{ {
return false; return false;
} }
surfaceOutputSettings ??= new SurfaceOutputSettings();
var imageEncoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(ie => ie.FilenameExtension.ToLowerInvariant().Contains(extension)); var imageEncoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(ie => ie.FilenameExtension.ToLowerInvariant().Contains(extension));
if (imageEncoder == null) if (imageEncoder == null)
{ {
@ -76,7 +77,7 @@ namespace Greenshot.Editor.FileFormatHandlers
{ {
Param = Param =
{ {
[0] = new EncoderParameter(Encoder.Quality, CoreConfig.OutputFileJpegQuality) [0] = new EncoderParameter(Encoder.Quality, surfaceOutputSettings.JPGQuality)
} }
}; };
// For those images which are with Alpha, but the format doesn't support this, change it to 24bpp // For those images which are with Alpha, but the format doesn't support this, change it to 24bpp

View file

@ -27,6 +27,7 @@ using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Plugin;
using Greenshot.Base.UnmanagedHelpers; using Greenshot.Base.UnmanagedHelpers;
using log4net; using log4net;
@ -40,7 +41,7 @@ namespace Greenshot.Editor.FileFormatHandlers
private const double DpiToPelsPerMeter = 39.3701; private const double DpiToPelsPerMeter = 39.3701;
private static readonly ILog Log = LogManager.GetLogger(typeof(DibFileFormatHandler)); private static readonly ILog Log = LogManager.GetLogger(typeof(DibFileFormatHandler));
private readonly List<string> _ourExtensions = new() { ".dib", ".format17" }; private readonly IReadOnlyCollection<string> _ourExtensions = new[] { ".dib", ".format17" };
public DibFileFormatHandler() public DibFileFormatHandler()
{ {
@ -50,7 +51,7 @@ namespace Greenshot.Editor.FileFormatHandlers
} }
/// <inheritdoc /> /// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
var dibBytes = ConvertToDib(bitmap); var dibBytes = ConvertToDib(bitmap);
destination.Write(dibBytes, 0, dibBytes.Length); destination.Write(dibBytes, 0, dibBytes.Length);

View file

@ -28,6 +28,7 @@ using System.Reflection;
using System.Text; using System.Text;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Plugin;
using log4net; using log4net;
namespace Greenshot.Editor.FileFormatHandlers namespace Greenshot.Editor.FileFormatHandlers
@ -35,7 +36,7 @@ namespace Greenshot.Editor.FileFormatHandlers
public class GreenshotFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler public class GreenshotFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(GreenshotFileFormatHandler)); private static readonly ILog Log = LogManager.GetLogger(typeof(GreenshotFileFormatHandler));
private readonly List<string> _ourExtensions = new() { ".greenshot" }; private readonly IReadOnlyCollection<string> _ourExtensions = new [] { ".greenshot" };
public GreenshotFileFormatHandler() public GreenshotFileFormatHandler()
{ {
SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions; SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions;
@ -43,7 +44,7 @@ namespace Greenshot.Editor.FileFormatHandlers
SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions; SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions;
} }
public override bool TrySaveToStream(Bitmap bitmap, Stream stream, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream stream, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
if (surface == null) if (surface == null)
{ {
@ -112,11 +113,11 @@ namespace Greenshot.Editor.FileFormatHandlers
} }
Log.InfoFormat("Greenshot file format: {0}", greenshotMarker); Log.InfoFormat("Greenshot file format: {0}", greenshotMarker);
const int filesizeLocation = 8 + markerSize; const int fileSizeLocation = 8 + markerSize;
surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End); surfaceFileStream.Seek(-fileSizeLocation, SeekOrigin.End);
using BinaryReader reader = new BinaryReader(surfaceFileStream); using BinaryReader reader = new BinaryReader(surfaceFileStream);
long bytesWritten = reader.ReadInt64(); long bytesWritten = reader.ReadInt64();
surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End); surfaceFileStream.Seek(-(bytesWritten + fileSizeLocation), SeekOrigin.End);
returnSurface.LoadElementsFromStream(surfaceFileStream); returnSurface.LoadElementsFromStream(surfaceFileStream);
} }

View file

@ -26,6 +26,7 @@ using System.Drawing.Imaging;
using System.IO; using System.IO;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Plugin;
using log4net; using log4net;
namespace Greenshot.Editor.FileFormatHandlers namespace Greenshot.Editor.FileFormatHandlers
@ -37,7 +38,7 @@ namespace Greenshot.Editor.FileFormatHandlers
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(IconFileFormatHandler)); private static readonly ILog Log = LogManager.GetLogger(typeof(IconFileFormatHandler));
private readonly List<string> _ourExtensions = new() { ".ico" }; private readonly IReadOnlyCollection<string> _ourExtensions = new[] { ".ico" };
public IconFileFormatHandler() public IconFileFormatHandler()
{ {
@ -46,7 +47,7 @@ namespace Greenshot.Editor.FileFormatHandlers
SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions; SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions;
} }
public override bool TrySaveToStream(Bitmap bitmap, Stream stream, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream stream, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
IList<Image> images = new List<Image> IList<Image> images = new List<Image>
{ {

View file

@ -26,6 +26,7 @@ using System.IO;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Drawing; using Greenshot.Base.Interfaces.Drawing;
using Greenshot.Base.Interfaces.Plugin;
using Greenshot.Editor.Drawing; using Greenshot.Editor.Drawing;
namespace Greenshot.Editor.FileFormatHandlers namespace Greenshot.Editor.FileFormatHandlers
@ -35,7 +36,7 @@ namespace Greenshot.Editor.FileFormatHandlers
/// </summary> /// </summary>
public class MetaFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler public class MetaFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler
{ {
private readonly List<string> _ourExtensions = new (){ ".wmf", ".emf" }; private readonly IReadOnlyCollection<string> _ourExtensions = new[] { ".wmf", ".emf" };
public MetaFileFormatHandler() public MetaFileFormatHandler()
{ {
@ -44,7 +45,7 @@ namespace Greenshot.Editor.FileFormatHandlers
} }
/// <inheritdoc /> /// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
return false; return false;
} }
@ -69,16 +70,12 @@ namespace Greenshot.Editor.FileFormatHandlers
} }
/// <inheritdoc /> /// <inheritdoc />
public override bool TryLoadDrawableFromStream(Stream stream, string extension, out IDrawableContainer drawableContainer, ISurface surface = null) public override IEnumerable<IDrawableContainer> LoadDrawablesFromStream(Stream stream, string extension, ISurface surface = null)
{ {
if (Image.FromStream(stream, true, true) is Metafile metaFile) if (Image.FromStream(stream, true, true) is Metafile metaFile)
{ {
drawableContainer = new MetafileContainer(metaFile, surface); yield return new MetafileContainer(metaFile, surface);
return true;
} }
drawableContainer = null;
return false;
} }
} }
} }

View file

@ -25,6 +25,7 @@ using System.Drawing;
using System.IO; using System.IO;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Drawing; using Greenshot.Base.Interfaces.Drawing;
using Greenshot.Base.Interfaces.Plugin;
using Greenshot.Editor.Drawing; using Greenshot.Editor.Drawing;
using log4net; using log4net;
using Svg; using Svg;
@ -37,7 +38,7 @@ namespace Greenshot.Editor.FileFormatHandlers
public class SvgFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler public class SvgFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(SvgFileFormatHandler)); private static readonly ILog Log = LogManager.GetLogger(typeof(SvgFileFormatHandler));
private readonly List<string> _ourExtensions = new() { ".svg" }; private readonly IReadOnlyCollection<string> _ourExtensions = new[] { ".svg" };
public SvgFileFormatHandler() public SvgFileFormatHandler()
{ {
@ -62,29 +63,27 @@ namespace Greenshot.Editor.FileFormatHandlers
return false; return false;
} }
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
// TODO: Implement this // TODO: Implement this
return false; return false;
} }
public override bool TryLoadDrawableFromStream(Stream stream, string extension, out IDrawableContainer drawableContainer, ISurface parent = null) public override IEnumerable<IDrawableContainer> LoadDrawablesFromStream(Stream stream, string extension, ISurface parent = null)
{ {
SvgDocument svgDocument = null;
try try
{ {
var svgDocument = SvgDocument.Open<SvgDocument>(stream); svgDocument = SvgDocument.Open<SvgDocument>(stream);
if (svgDocument != null)
{
drawableContainer = new SvgContainer(svgDocument, parent);
return true;
}
} }
catch (Exception ex) catch (Exception ex)
{ {
Log.Error("Can't load SVG", ex); Log.Error("Can't load SVG", ex);
} }
drawableContainer = null; if (svgDocument != null)
return true; {
yield return new SvgContainer(svgDocument, parent);
}
} }
} }
} }

View file

@ -21,11 +21,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using Greenshot.Base.Interfaces.Plugin;
using log4net; using log4net;
namespace Greenshot.Editor.FileFormatHandlers namespace Greenshot.Editor.FileFormatHandlers
@ -36,8 +38,8 @@ namespace Greenshot.Editor.FileFormatHandlers
public class WpfFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler public class WpfFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(WpfFileFormatHandler)); private static readonly ILog Log = LogManager.GetLogger(typeof(WpfFileFormatHandler));
private List<string> LoadFromStreamExtensions { get; } = new() { ".jxr", ".wdp", ".wmp", ".heic", ".heif" }; private IReadOnlyCollection<string> LoadFromStreamExtensions { get; } = new []{ ".jxr", ".wdp", ".wmp", ".heic", ".heif" };
private List<string> SaveToStreamExtensions { get; } = new() { ".jxr" }; private IReadOnlyCollection<string> SaveToStreamExtensions { get; } = new[] { ".jxr" };
public WpfFileFormatHandler() public WpfFileFormatHandler()
{ {
@ -47,8 +49,9 @@ namespace Greenshot.Editor.FileFormatHandlers
} }
/// <inheritdoc /> /// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null) public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null)
{ {
surfaceOutputSettings ??= new SurfaceOutputSettings();
try try
{ {
var bitmapSource = bitmap.ToBitmapSource(); var bitmapSource = bitmap.ToBitmapSource();
@ -56,7 +59,7 @@ namespace Greenshot.Editor.FileFormatHandlers
var jpegXrEncoder = new WmpBitmapEncoder(); var jpegXrEncoder = new WmpBitmapEncoder();
jpegXrEncoder.Frames.Add(bitmapFrame); jpegXrEncoder.Frames.Add(bitmapFrame);
// TODO: Support supplying a quality // TODO: Support supplying a quality
//jpegXrEncoder.ImageQualityLevel = quality / 100f; jpegXrEncoder.ImageQualityLevel = surfaceOutputSettings.JPGQuality / 100f;
jpegXrEncoder.Save(destination); jpegXrEncoder.Save(destination);
return true; return true;
} }

View file

@ -1257,7 +1257,7 @@ namespace Greenshot.Forms {
// //
// SettingsForm // SettingsForm
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(451, 431); this.ClientSize = new System.Drawing.Size(451, 431);
this.Controls.Add(this.tabcontrol); this.Controls.Add(this.tabcontrol);