Making the save functionality in the editor work with the new IFileFormatHandler, the file dialog still needs to be adjusted.

This commit is contained in:
Robin Krom 2022-02-10 23:43:28 +01:00
commit bb39817f9d
No known key found for this signature in database
GPG key ID: BCC01364F1371490
13 changed files with 210 additions and 153 deletions

View file

@ -120,6 +120,7 @@ namespace Greenshot.Base.Controls
private void PrepareFilterOptions()
{
// TODO: Change to the FileFormatHandlerRegistry to look for all the supported extensions
OutputFormat[] supportedImageFormats = (OutputFormat[]) Enum.GetValues(typeof(OutputFormat));
_filterOptions = new FilterOption[supportedImageFormats.Length];
for (int i = 0; i < _filterOptions.Length; i++)

View file

@ -83,7 +83,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers
/// <param name="destination">Stream</param>
/// <param name="extension">string</param>
/// <returns>bool</returns>
public static bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public static bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null)
{
extension = NormalizeExtension(extension);
@ -97,7 +97,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers
return false;
}
return fileFormatHandler.TrySaveToStream(bitmap, destination, extension);
return fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface);
}
/// <summary>

View file

@ -33,11 +33,11 @@ using System.Text.RegularExpressions;
using System.Windows.Forms;
using Greenshot.Base.Controls;
using Greenshot.Base.Core.Enums;
using Greenshot.Base.Core.FileFormatHandlers;
using Greenshot.Base.IniFile;
using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Plugin;
using log4net;
using Encoder = System.Drawing.Imaging.Encoder;
namespace Greenshot.Base.Core
{
@ -54,7 +54,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// Creates a PropertyItem (Metadata) to store with the image.
/// For the possible ID's see: https://msdn.microsoft.com/de-de/library/system.drawing.imaging.propertyitem.id(v=vs.80).aspx
/// This code uses Reflection to create a PropertyItem, although it's not adviced it's not as stupid as having a image in the project so we can read a PropertyItem from that!
/// This code uses Reflection to create a PropertyItem, although it's not advised it's not as stupid as having a image in the project so we can read a PropertyItem from that!
/// </summary>
/// <param name="id">ID</param>
/// <param name="text">Text</param>
@ -124,102 +124,21 @@ namespace Greenshot.Base.Core
try
{
var imageFormat = outputSettings.Format switch
{
OutputFormat.bmp => ImageFormat.Bmp,
OutputFormat.gif => ImageFormat.Gif,
OutputFormat.jpg => ImageFormat.Jpeg,
OutputFormat.tiff => ImageFormat.Tiff,
OutputFormat.ico => ImageFormat.Icon,
_ => ImageFormat.Png
};
Log.DebugFormat("Saving image to stream with Format {0} and PixelFormat {1}", imageFormat, imageToSave.PixelFormat);
// Check if we want to use a memory stream, to prevent issues with non seakable streams
// The save is made to the targetStream, this is directed to either the MemoryStream or the original
Stream targetStream = stream;
if (!stream.CanSeek)
{
useMemoryStream = true;
Log.Warn("Using memorystream prevent an issue with saving to a non seekable stream.");
Log.Warn("Using a memory stream prevent an issue with saving to a non seekable stream.");
memoryStream = new MemoryStream();
targetStream = memoryStream;
}
if (Equals(imageFormat, ImageFormat.Jpeg))
if (!FileFormatHandlerRegistry.TrySaveToStream(imageToSave as Bitmap, targetStream, outputSettings.Format.ToString(), surface))
{
bool foundEncoder = false;
foreach (ImageCodecInfo imageCodec in ImageCodecInfo.GetImageEncoders())
{
if (imageCodec.FormatID == imageFormat.Guid)
{
EncoderParameters parameters = new EncoderParameters(1)
{
Param =
{
[0] = new EncoderParameter(Encoder.Quality, outputSettings.JPGQuality)
}
};
// Removing transparency if it's not supported in the output
if (Image.IsAlphaPixelFormat(imageToSave.PixelFormat))
{
Image nonAlphaImage = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
AddTag(nonAlphaImage);
nonAlphaImage.Save(targetStream, imageCodec, parameters);
nonAlphaImage.Dispose();
}
else
{
AddTag(imageToSave);
imageToSave.Save(targetStream, imageCodec, parameters);
}
foundEncoder = true;
break;
}
}
if (!foundEncoder)
{
throw new ApplicationException("No JPG encoder found, this should not happen.");
}
}
else if (Equals(imageFormat, ImageFormat.Icon))
{
// FEATURE-916: Added Icon support
IList<Image> images = new List<Image>
{
imageToSave
};
WriteIcon(stream, images);
}
else
{
bool needsDispose = false;
// Removing transparency if it's not supported in the output
if (!Equals(imageFormat, ImageFormat.Png) && Image.IsAlphaPixelFormat(imageToSave.PixelFormat))
{
imageToSave = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
needsDispose = true;
}
AddTag(imageToSave);
// Added for OptiPNG
bool processed = false;
if (Equals(imageFormat, ImageFormat.Png) && !string.IsNullOrEmpty(CoreConfig.OptimizePNGCommand))
{
processed = ProcessPngImageExternally(imageToSave, targetStream);
}
if (!processed)
{
imageToSave.Save(targetStream, imageFormat);
}
if (needsDispose)
{
imageToSave.Dispose();
}
return;
}
// If we used a memory stream, we need to stream the memory stream to the original stream.
@ -227,21 +146,6 @@ namespace Greenshot.Base.Core
{
memoryStream.WriteTo(stream);
}
// Output the surface elements, size and marker to the stream
if (outputSettings.Format != OutputFormat.greenshot)
{
return;
}
using MemoryStream tmpStream = new MemoryStream();
long bytesWritten = surface.SaveElementsToStream(tmpStream);
using BinaryWriter writer = new BinaryWriter(tmpStream);
writer.Write(bytesWritten);
Version v = Assembly.GetExecutingAssembly().GetName().Version;
byte[] marker = Encoding.ASCII.GetBytes($"Greenshot{v.Major:00}.{v.Minor:00}");
writer.Write(marker);
tmpStream.WriteTo(stream);
}
finally
{
@ -429,20 +333,18 @@ namespace Greenshot.Base.Core
/// Add the greenshot property!
/// </summary>
/// <param name="imageToSave"></param>
private static void AddTag(Image imageToSave)
public static void AddTag(this Image imageToSave)
{
// Create meta-data
PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot");
if (softwareUsedPropertyItem != null)
if (softwareUsedPropertyItem == null) return;
try
{
try
{
imageToSave.SetPropertyItem(softwareUsedPropertyItem);
}
catch (Exception)
{
Log.WarnFormat("Couldn't set property {0}", softwareUsedPropertyItem.Id);
}
imageToSave.SetPropertyItem(softwareUsedPropertyItem);
}
catch (Exception)
{
Log.WarnFormat("Couldn't set property {0}", softwareUsedPropertyItem.Id);
}
}
@ -547,27 +449,25 @@ namespace Greenshot.Base.Core
using (SaveImageFileDialog saveImageFileDialog = new SaveImageFileDialog(captureDetails))
{
DialogResult dialogResult = saveImageFileDialog.ShowDialog();
if (dialogResult.Equals(DialogResult.OK))
if (!dialogResult.Equals(DialogResult.OK)) return returnValue;
try
{
try
string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension;
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(FormatForFilename(fileNameWithExtension));
if (CoreConfig.OutputFilePromptQuality)
{
string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension;
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(FormatForFilename(fileNameWithExtension));
if (CoreConfig.OutputFilePromptQuality)
{
QualityDialog qualityDialog = new QualityDialog(outputSettings);
qualityDialog.ShowDialog();
}
QualityDialog qualityDialog = new QualityDialog(outputSettings);
qualityDialog.ShowDialog();
}
// TODO: For now we always overwrite, should be changed
Save(surface, fileNameWithExtension, true, outputSettings, CoreConfig.OutputFileCopyPathToClipboard);
returnValue = fileNameWithExtension;
IniConfig.Save();
}
catch (ExternalException)
{
MessageBox.Show(Language.GetFormattedString("error_nowriteaccess", saveImageFileDialog.FileName).Replace(@"\\", @"\"), Language.GetString("error"));
}
// TODO: For now we always overwrite, should be changed
Save(surface, fileNameWithExtension, true, outputSettings, CoreConfig.OutputFileCopyPathToClipboard);
returnValue = fileNameWithExtension;
IniConfig.Save();
}
catch (ExternalException)
{
MessageBox.Show(Language.GetFormattedString("error_nowriteaccess", saveImageFileDialog.FileName).Replace(@"\\", @"\"), Language.GetString("error"));
}
}

View file

@ -61,8 +61,9 @@ namespace Greenshot.Base.Interfaces
/// <param name="bitmap">Bitmap</param>
/// <param name="destination">Stream</param>
/// <param name="extension">extension</param>
/// <param name="surface">ISurface</param>
/// <returns>bool true if it was successful</returns>
public bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension);
public bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface);
/// <summary>
///

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 System.Drawing;
using System.IO;
using Greenshot.Base.Interfaces;
@ -18,7 +39,8 @@ namespace Greenshot.Editor.FileFormatHandlers
return 0;
}
public abstract bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension);
public abstract bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null);
public abstract bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap);
/// <summary>

View file

@ -23,7 +23,10 @@ using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Greenshot.Base.Core;
using Greenshot.Base.Core.FileFormatHandlers;
using Greenshot.Base.IniFile;
using Greenshot.Base.Interfaces;
namespace Greenshot.Editor.FileFormatHandlers
@ -34,7 +37,7 @@ namespace Greenshot.Editor.FileFormatHandlers
public class DefaultFileFormatHandler : AbstractFileFormatHandler, IFileFormatHandler
{
private readonly List<string> _ourExtensions = new() { ".png", ".bmp", ".gif", ".jpg", ".jpeg", ".tiff", ".tif" };
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
public DefaultFileFormatHandler()
{
SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions;
@ -43,7 +46,7 @@ namespace Greenshot.Editor.FileFormatHandlers
}
/// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null)
{
ImageFormat imageFormat = extension switch
{
@ -61,7 +64,41 @@ namespace Greenshot.Editor.FileFormatHandlers
{
return false;
}
bitmap.Save(destination, imageFormat);
var imageEncoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(ie => ie.FilenameExtension.ToLowerInvariant().Contains(extension));
if (imageEncoder == null)
{
return false;
}
EncoderParameters parameters = new EncoderParameters(1)
{
Param =
{
[0] = new EncoderParameter(Encoder.Quality, CoreConfig.OutputFileJpegQuality)
}
};
// For those images which are with Alpha, but the format doesn't support this, change it to 24bpp
if (imageFormat.Guid == ImageFormat.Jpeg.Guid && Image.IsAlphaPixelFormat(bitmap.PixelFormat))
{
var nonAlphaImage = ImageHelper.Clone(bitmap, PixelFormat.Format24bppRgb) as Bitmap;
try
{
// Set that this file was written by Greenshot
nonAlphaImage.AddTag();
nonAlphaImage.Save(destination, imageEncoder, parameters);
}
finally
{
nonAlphaImage.Dispose();
}
}
else
{
// Set that this file was written by Greenshot
bitmap.AddTag();
bitmap.Save(destination, imageEncoder, parameters);
}
return true;
}

View file

@ -50,7 +50,7 @@ namespace Greenshot.Editor.FileFormatHandlers
}
/// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null)
{
var dibBytes = ConvertToDib(bitmap);
destination.Write(dibBytes, 0, dibBytes.Length);

View file

@ -22,7 +22,10 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;
using Greenshot.Base.Core;
using Greenshot.Base.Interfaces;
@ -35,12 +38,21 @@ namespace Greenshot.Editor.FileFormatHandlers
{
SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions;
SupportedExtensions[FileFormatHandlerActions.LoadFromStream] = _ourExtensions;
//SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions;
SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions;
}
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream stream, string extension, ISurface surface = null)
{
throw new NotImplementedException();
bitmap.Save(stream, ImageFormat.Png);
using MemoryStream tmpStream = new MemoryStream();
long bytesWritten = surface.SaveElementsToStream(tmpStream);
using BinaryWriter writer = new BinaryWriter(tmpStream);
writer.Write(bytesWritten);
Version v = Assembly.GetExecutingAssembly().GetName().Version;
byte[] marker = Encoding.ASCII.GetBytes($"Greenshot{v.Major:00}.{v.Minor:00}");
writer.Write(marker);
tmpStream.WriteTo(stream);
return true;
}
public override bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap)
@ -49,6 +61,5 @@ namespace Greenshot.Editor.FileFormatHandlers
bitmap = (Bitmap)surface.GetImageForExport();
return true;
}
}
}

View file

@ -43,12 +43,97 @@ namespace Greenshot.Editor.FileFormatHandlers
{
SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = _ourExtensions;
SupportedExtensions[FileFormatHandlerActions.LoadFromStream] = _ourExtensions;
SupportedExtensions[FileFormatHandlerActions.SaveToStream] = _ourExtensions;
}
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream stream, string extension, ISurface surface = null)
{
IList<Image> images = new List<Image>
{
bitmap
};
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();
}
// TODO: Implement this
return false;
return true;
}
public override bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap)

View file

@ -45,7 +45,7 @@ namespace Greenshot.Editor.FileFormatHandlers
}
/// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null)
{
return false;
}

View file

@ -62,7 +62,7 @@ namespace Greenshot.Editor.FileFormatHandlers
return false;
}
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null)
{
// TODO: Implement this
return false;

View file

@ -44,7 +44,7 @@ namespace Greenshot.Editor.FileFormatHandlers
}
/// <inheritdoc />
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension)
public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null)
{
try
{

View file

@ -923,11 +923,11 @@ namespace Greenshot.Forms
{
Hide();
ShowInTaskbar = false;
using var loProcess = Process.GetCurrentProcess();
loProcess.MaxWorkingSet = (IntPtr)750000;
loProcess.MinWorkingSet = (IntPtr)300000;
// TODO: Do we really need this?
//using var loProcess = Process.GetCurrentProcess();
//loProcess.MaxWorkingSet = (IntPtr)750000;
//loProcess.MinWorkingSet = (IntPtr)300000;
}
private void CaptureRegion()