Refactoring which replaces the Image in the ImageOutput for an ISurface, this makes it possible to save the Surface to any possible file format and even make it possible to pass some additional information in the OutputSettings. (Except reducing the colors, there are no other settings yet)

git-svn-id: http://svn.code.sf.net/p/greenshot/code/trunk@2376 7dccd23d-a4a3-4e1f-8c07-b4c1b4018ab4
This commit is contained in:
RKrom 2012-12-11 14:36:20 +00:00
parent e11450f56f
commit 5541e2e1c7
27 changed files with 191 additions and 290 deletions

View file

@ -71,10 +71,8 @@ namespace Greenshot.Destinations {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
try { try {
using (Image image = surface.GetImageForExport()) { ClipboardHelper.SetClipboardData(surface);
ClipboardHelper.SetClipboardData(image); exportInformation.ExportMade = true;
exportInformation.ExportMade = true;
}
} catch (Exception) { } catch (Exception) {
// TODO: Change to general logic in ProcessExport // TODO: Change to general logic in ProcessExport
surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetString(LangKey.editor_clipboardfailed)); surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetString(LangKey.editor_clipboardfailed));

View file

@ -55,12 +55,10 @@ namespace GreenshotBoxPlugin {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { string uploadUrl = plugin.Upload(captureDetails, surface);
string uploadUrl = plugin.Upload(captureDetails, image); if (uploadUrl != null) {
if (uploadUrl != null) { exportInformation.ExportMade = true;
exportInformation.ExportMade = true; exportInformation.Uri = uploadUrl;
exportInformation.Uri = uploadUrl;
}
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;

View file

@ -110,12 +110,12 @@ namespace GreenshotBoxPlugin {
/// <summary> /// <summary>
/// This will be called when the menu item in the Editor is clicked /// This will be called when the menu item in the Editor is clicked
/// </summary> /// </summary>
public string Upload(ICaptureDetails captureDetails, Image image) { public string Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload) {
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, false); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, false);
try { try {
string url = null; string url = null;
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
ImageContainer imageToUpload = new ImageContainer(image, outputSettings, filename); SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
new PleaseWaitForm().ShowAndWait(BoxPlugin.Attributes.Name, Language.GetString("box", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(BoxPlugin.Attributes.Name, Language.GetString("box", LangKey.communication_wait),
delegate() { delegate() {

View file

@ -92,7 +92,7 @@ namespace GreenshotBoxPlugin {
/// </summary> /// </summary>
/// <param name="imageData">byte[] with image data</param> /// <param name="imageData">byte[] with image data</param>
/// <returns>url to uploaded image</returns> /// <returns>url to uploaded image</returns>
public static string UploadToBox(ImageContainer image, string title, string filename) { public static string UploadToBox(SurfaceContainer image, string title, string filename) {
string folderId = "0"; string folderId = "0";
if (string.IsNullOrEmpty(config.BoxToken)) { if (string.IsNullOrEmpty(config.BoxToken)) {
if (!Authorize()) { if (!Authorize()) {

View file

@ -136,33 +136,31 @@ namespace GreenshotConfluencePlugin {
} }
} }
if (selectedPage != null) { if (selectedPage != null) {
using (Image image = surface.GetImageForExport()) { string errorMessage;
string errorMessage; bool uploaded = upload(surface, selectedPage, filename, out errorMessage);
bool uploaded = upload(image, selectedPage, filename, out errorMessage); if (uploaded) {
if (uploaded) { if (openPage) {
if (openPage) { try {
try { Process.Start(selectedPage.Url);
Process.Start(selectedPage.Url); } catch { }
} catch { }
}
exportInformation.ExportMade = true;
exportInformation.Uri = selectedPage.Url;
} else {
exportInformation.ErrorMessage = errorMessage;
} }
exportInformation.ExportMade = true;
exportInformation.Uri = selectedPage.Url;
} else {
exportInformation.ErrorMessage = errorMessage;
} }
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;
} }
private bool upload(Image image, Page page, string filename, out string errorMessage) { private bool upload(ISurface surfaceToUpload, Page page, string filename, out string errorMessage) {
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);
errorMessage = null; errorMessage = null;
try { try {
new PleaseWaitForm().ShowAndWait(Description, Language.GetString("confluence", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(Description, Language.GetString("confluence", LangKey.communication_wait),
delegate() { delegate() {
ConfluencePlugin.ConfluenceConnector.addAttachment(page.id, "image/" + config.UploadFormat.ToString().ToLower(), null, filename, new ImageContainer(image, outputSettings, filename)); ConfluencePlugin.ConfluenceConnector.addAttachment(page.id, "image/" + config.UploadFormat.ToString().ToLower(), null, filename, new SurfaceContainer(surfaceToUpload, outputSettings, filename));
} }
); );
LOG.Debug("Uploaded to Confluence."); LOG.Debug("Uploaded to Confluence.");

View file

@ -54,15 +54,13 @@ namespace GreenshotDropboxPlugin {
public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { string uploadURL = null;
string uploadURL = null; bool uploaded = plugin.Upload(captureDetails, surface, out uploadURL);
bool uploaded = plugin.Upload(captureDetails, image, out uploadURL); if (uploaded) {
if (uploaded) { exportInformation.Uri = uploadURL;
exportInformation.Uri = uploadURL; exportInformation.ExportMade = true;
exportInformation.ExportMade = true; if (config.AfterUploadLinkToClipBoard) {
if (config.AfterUploadLinkToClipBoard) { ClipboardHelper.SetClipboardData(uploadURL);
ClipboardHelper.SetClipboardData(uploadURL);
}
} }
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);

View file

@ -111,7 +111,7 @@ namespace GreenshotDropboxPlugin {
/// <summary> /// <summary>
/// This will be called when the menu item in the Editor is clicked /// This will be called when the menu item in the Editor is clicked
/// </summary> /// </summary>
public bool Upload(ICaptureDetails captureDetails, Image image, out string uploadUrl) { public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) {
uploadUrl = null; uploadUrl = null;
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, false); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, false);
try { try {
@ -119,7 +119,7 @@ namespace GreenshotDropboxPlugin {
new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("dropbox", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("dropbox", LangKey.communication_wait),
delegate() { delegate() {
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
dropboxUrl = DropboxUtils.UploadToDropbox(image, outputSettings, filename); dropboxUrl = DropboxUtils.UploadToDropbox(surfaceToUpload, outputSettings, filename);
} }
); );
if (dropboxUrl == null) { if (dropboxUrl == null) {

View file

@ -36,7 +36,7 @@ namespace GreenshotDropboxPlugin {
private DropboxUtils() { private DropboxUtils() {
} }
public static string UploadToDropbox(Image image, OutputSettings outputSettings, string filename) { public static string UploadToDropbox(ISurface surfaceToUpload, OutputSettings outputSettings, string filename) {
OAuthSession oAuth = new OAuthSession(DropBoxCredentials.CONSUMER_KEY, DropBoxCredentials.CONSUMER_SECRET); OAuthSession oAuth = new OAuthSession(DropBoxCredentials.CONSUMER_KEY, DropBoxCredentials.CONSUMER_SECRET);
oAuth.BrowserSize = new Size(1080, 650); oAuth.BrowserSize = new Size(1080, 650);
oAuth.CheckVerifier = false; oAuth.CheckVerifier = false;
@ -48,7 +48,7 @@ namespace GreenshotDropboxPlugin {
oAuth.TokenSecret = config.DropboxTokenSecret; oAuth.TokenSecret = config.DropboxTokenSecret;
try { try {
ImageContainer imageToUpload = new ImageContainer(image, outputSettings, filename); SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename);
string uploadResponse = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://api-content.dropbox.com/1/files_put/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, imageToUpload); string uploadResponse = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://api-content.dropbox.com/1/files_put/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, imageToUpload);
LOG.DebugFormat("Upload response: {0}", uploadResponse); LOG.DebugFormat("Upload response: {0}", uploadResponse);
} catch (Exception ex) { } catch (Exception ex) {

View file

@ -54,9 +54,7 @@ namespace GreenshotFlickrPlugin {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { plugin.Upload(captureDetails, surface, exportInformation);
plugin.Upload(captureDetails, image, exportInformation);
}
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;
} }

View file

@ -110,14 +110,14 @@ namespace GreenshotFlickrPlugin
config.ShowConfigDialog(); config.ShowConfigDialog();
} }
public void Upload(ICaptureDetails captureDetails, Image image, ExportInformation exportInformation) { public void Upload(ICaptureDetails captureDetails, ISurface surface, ExportInformation exportInformation) {
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, false); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, false);
try { try {
string flickrUrl = null; string flickrUrl = null;
new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("flickr", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("flickr", LangKey.communication_wait),
delegate() { delegate() {
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
flickrUrl = FlickrUtils.UploadToFlickr(image, outputSettings, captureDetails.Title, filename); flickrUrl = FlickrUtils.UploadToFlickr(surface, outputSettings, captureDetails.Title, filename);
} }
); );

View file

@ -44,7 +44,7 @@ namespace GreenshotFlickrPlugin {
/// </summary> /// </summary>
/// <param name="imageData">byte[] with image data</param> /// <param name="imageData">byte[] with image data</param>
/// <returns>url to image</returns> /// <returns>url to image</returns>
public static string UploadToFlickr(Image image, OutputSettings outputSettings, string title, string filename) { public static string UploadToFlickr(ISurface surfaceToUpload, OutputSettings outputSettings, string title, string filename) {
OAuthSession oAuth = new OAuthSession(FlickrCredentials.ConsumerKey, FlickrCredentials.ConsumerSecret); OAuthSession oAuth = new OAuthSession(FlickrCredentials.ConsumerKey, FlickrCredentials.ConsumerSecret);
oAuth.BrowserSize = new Size(520, 800); oAuth.BrowserSize = new Size(520, 800);
oAuth.CheckVerifier = false; oAuth.CheckVerifier = false;
@ -76,7 +76,7 @@ namespace GreenshotFlickrPlugin {
signedParameters.Add("safety_level", string.Format("{0}", (int)config.SafetyLevel)); signedParameters.Add("safety_level", string.Format("{0}", (int)config.SafetyLevel));
signedParameters.Add("hidden", config.HiddenFromSearch?"1":"2"); signedParameters.Add("hidden", config.HiddenFromSearch?"1":"2");
IDictionary<string, object> otherParameters = new Dictionary<string, object>(); IDictionary<string, object> otherParameters = new Dictionary<string, object>();
otherParameters.Add("photo", new ImageContainer(image, outputSettings, filename)); otherParameters.Add("photo", new SurfaceContainer(surfaceToUpload, outputSettings, filename));
string response = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.flickr.com/services/upload/", signedParameters, otherParameters, null); string response = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.flickr.com/services/upload/", signedParameters, otherParameters, null);
string photoId = GetPhotoId(response); string photoId = GetPhotoId(response);

View file

@ -58,11 +58,9 @@ namespace GreenshotImgurPlugin {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { string uploadURL = null;
string uploadURL = null; exportInformation.ExportMade = plugin.Upload(captureDetails, surface, out uploadURL);
exportInformation.ExportMade = plugin.Upload(captureDetails, image, out uploadURL); exportInformation.Uri = uploadURL;
exportInformation.Uri = uploadURL;
}
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;
} }

View file

@ -151,7 +151,7 @@ namespace GreenshotImgurPlugin {
/// <param name="image"></param> /// <param name="image"></param>
/// <param name="uploadURL">out string for the url</param> /// <param name="uploadURL">out string for the url</param>
/// <returns>true if the upload succeeded</returns> /// <returns>true if the upload succeeded</returns>
public bool Upload(ICaptureDetails captureDetails, Image image, out string uploadURL) { public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadURL) {
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);
try { try {
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
@ -160,7 +160,7 @@ namespace GreenshotImgurPlugin {
// Run upload in the background // Run upload in the background
new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("imgur", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("imgur", LangKey.communication_wait),
delegate() { delegate() {
imgurInfo = ImgurUtils.UploadToImgur(image, outputSettings, captureDetails.Title, filename); imgurInfo = ImgurUtils.UploadToImgur(surfaceToUpload, outputSettings, captureDetails.Title, filename);
LOG.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash); LOG.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash);
config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash); config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash);
config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo); config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo);
@ -168,7 +168,10 @@ namespace GreenshotImgurPlugin {
} }
); );
imgurInfo.Image = ImageHelper.CreateThumbnail(image, 90, 90); // TODO: Optimize a second call for export
using (Image tmpImage = surfaceToUpload.GetImageForExport()) {
imgurInfo.Image = ImageHelper.CreateThumbnail(tmpImage, 90, 90);
}
IniConfig.Save(); IniConfig.Save();
uploadURL = null; uploadURL = null;
try { try {

View file

@ -94,12 +94,12 @@ namespace GreenshotImgurPlugin {
/// Do the actual upload to Imgur /// Do the actual upload to Imgur
/// For more details on the available parameters, see: http://api.imgur.com/resources_anon /// For more details on the available parameters, see: http://api.imgur.com/resources_anon
/// </summary> /// </summary>
/// <param name="image">Image to upload</param> /// <param name="surfaceToUpload">ISurface to upload</param>
/// <param name="outputSettings">OutputSettings for the image file format</param> /// <param name="outputSettings">OutputSettings for the image file format</param>
/// <param name="title">Title</param> /// <param name="title">Title</param>
/// <param name="filename">Filename</param> /// <param name="filename">Filename</param>
/// <returns>ImgurInfo with details</returns> /// <returns>ImgurInfo with details</returns>
public static ImgurInfo UploadToImgur(Image image, OutputSettings outputSettings, string title, string filename) { public static ImgurInfo UploadToImgur(ISurface surfaceToUpload, OutputSettings outputSettings, string title, string filename) {
IDictionary<string, object> uploadParameters = new Dictionary<string, object>(); IDictionary<string, object> uploadParameters = new Dictionary<string, object>();
IDictionary<string, object> otherParameters = new Dictionary<string, object>(); IDictionary<string, object> otherParameters = new Dictionary<string, object>();
// add title // add title
@ -120,7 +120,7 @@ namespace GreenshotImgurPlugin {
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
try { try {
using (var requestStream = webRequest.GetRequestStream()) { using (var requestStream = webRequest.GetRequestStream()) {
ImageOutput.SaveToStream(image, requestStream, outputSettings); ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings);
} }
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
@ -156,7 +156,7 @@ namespace GreenshotImgurPlugin {
IniConfig.Save(); IniConfig.Save();
} }
try { try {
otherParameters.Add("image", new ImageContainer(image, outputSettings, filename)); otherParameters.Add("image", new SurfaceContainer(surfaceToUpload, outputSettings, filename));
responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.imgur.com/2/account/images.xml", uploadParameters, otherParameters, null); responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.imgur.com/2/account/images.xml", uploadParameters, otherParameters, null);
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Upload to imgur gave an exeption: ", ex); LOG.Error("Upload to imgur gave an exeption: ", ex);

View file

@ -99,25 +99,24 @@ namespace GreenshotJiraPlugin {
} }
} }
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surfaceToUpload, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);
if (jira != null) { if (jira != null) {
using (Image image = surface.GetImageForExport()) { try {
try { // Run upload in the background
// Run upload in the background new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait),
new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait), delegate() {
delegate() { jiraPlugin.JiraConnector.addAttachment(jira.Key, filename, new SurfaceContainer(surfaceToUpload, outputSettings, filename));
jiraPlugin.JiraConnector.addAttachment(jira.Key, filename, new ImageContainer(image, outputSettings, filename)); }
} );
); LOG.Debug("Uploaded to Jira.");
LOG.Debug("Uploaded to Jira."); exportInformation.ExportMade = true;
exportInformation.ExportMade = true; // TODO: This can't work:
exportInformation.Uri = surface.UploadURL; exportInformation.Uri = surfaceToUpload.UploadURL;
} catch (Exception e) { } catch (Exception e) {
MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message); MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message);
}
} }
} else { } else {
JiraForm jiraForm = new JiraForm(jiraPlugin.JiraConnector); JiraForm jiraForm = new JiraForm(jiraPlugin.JiraConnector);
@ -126,24 +125,23 @@ namespace GreenshotJiraPlugin {
DialogResult result = jiraForm.ShowDialog(); DialogResult result = jiraForm.ShowDialog();
if (result == DialogResult.OK) { if (result == DialogResult.OK) {
try { try {
using (Image image = surface.GetImageForExport()) { // Run upload in the background
// Run upload in the background new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait),
new PleaseWaitForm().ShowAndWait(Description, Language.GetString("jira", LangKey.communication_wait), delegate() {
delegate() { jiraForm.upload(new SurfaceContainer(surfaceToUpload, outputSettings, filename));
jiraForm.upload(new ImageContainer(image, outputSettings, filename)); }
} );
);
}
LOG.Debug("Uploaded to Jira."); LOG.Debug("Uploaded to Jira.");
exportInformation.ExportMade = true; exportInformation.ExportMade = true;
exportInformation.Uri = surface.UploadURL; // TODO: This can't work:
exportInformation.Uri = surfaceToUpload.UploadURL;
} catch(Exception e) { } catch(Exception e) {
MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message); MessageBox.Show(Language.GetString("jira", LangKey.upload_failure) + " " + e.Message);
} }
} }
} }
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surfaceToUpload);
return exportInformation; return exportInformation;
} }
} }

View file

@ -138,24 +138,10 @@ namespace GreenshotOCR {
public string DoOCR(ISurface surface) { public string DoOCR(ISurface surface) {
string filePath = null; string filePath = null;
OutputSettings outputSettings = new OutputSettings(OutputFormat.bmp, 0, true); OutputSettings outputSettings = new OutputSettings(OutputFormat.bmp, 0, true);
// TODO: Add some filter & output settings so the output image is easier to process for the MODI-OCR code
// Also we need to check the size, resize if needed to 130x130 this is the minimum
filePath = ImageOutput.SaveToTmpFile(surface, outputSettings, null);
// Use surface background image, this prevents having a mouse cursor in the way.
Image capturedImage = surface.Image;
if (capturedImage.Width < MIN_WIDTH || capturedImage.Height < MIN_HEIGHT) {
LOG.Debug("Captured image is not big enough for OCR, growing image...");
int newWidth = Math.Max(capturedImage.Width, MIN_WIDTH);
int newHeight = Math.Max(capturedImage.Height, MIN_HEIGHT);
using (Image tmpImage = new Bitmap(newWidth, newHeight, capturedImage.PixelFormat)) {
using (Graphics graphics = Graphics.FromImage(tmpImage)) {
graphics.Clear(Color.White);
graphics.DrawImage(capturedImage, Point.Empty);
}
filePath = ImageOutput.SaveToTmpFile(tmpImage, outputSettings, null);
}
} else {
filePath = ImageOutput.SaveToTmpFile(capturedImage, outputSettings, null);
}
LOG.Debug("Saved tmp file to: " + filePath); LOG.Debug("Saved tmp file to: " + filePath);
string text = ""; string text = "";

View file

@ -109,15 +109,13 @@ namespace GreenshotOfficePlugin {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { if (page != null) {
if (page != null) { try {
try { OneNoteExporter.ExportToPage(surface, page);
OneNoteExporter.ExportToPage((Bitmap)image, page); exportInformation.ExportMade = true;
exportInformation.ExportMade = true; } catch (Exception ex) {
} catch (Exception ex) { exportInformation.ErrorMessage = ex.Message;
exportInformation.ErrorMessage = ex.Message; LOG.Error(ex);
LOG.Error(ex);
}
} }
} }
return exportInformation; return exportInformation;

View file

@ -43,12 +43,12 @@ namespace Greenshot.Interop.Office {
private const string ONENOTE_NAMESPACE_2007 = "http://schemas.microsoft.com/office/onenote/2007/onenote"; private const string ONENOTE_NAMESPACE_2007 = "http://schemas.microsoft.com/office/onenote/2007/onenote";
private const string ONENOTE_NAMESPACE_2010 = "http://schemas.microsoft.com/office/onenote/2010/onenote"; private const string ONENOTE_NAMESPACE_2010 = "http://schemas.microsoft.com/office/onenote/2010/onenote";
public static void ExportToPage(Bitmap imageToExport, OneNotePage page) { public static void ExportToPage(ISurface surfaceToUpload, OneNotePage page) {
using (MemoryStream pngStream = new MemoryStream()) { using (MemoryStream pngStream = new MemoryStream()) {
OutputSettings pngOutputSettings = new OutputSettings(OutputFormat.png, 100, false); OutputSettings pngOutputSettings = new OutputSettings(OutputFormat.png, 100, false);
ImageOutput.SaveToStream(imageToExport, pngStream, pngOutputSettings); ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings);
string base64String = Convert.ToBase64String(pngStream.GetBuffer()); string base64String = Convert.ToBase64String(pngStream.GetBuffer());
string imageXmlStr = string.Format(XML_IMAGE_CONTENT, base64String, imageToExport.Width, imageToExport.Height); string imageXmlStr = string.Format(XML_IMAGE_CONTENT, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height);
string pageChangesXml = string.Format(XML_OUTLINE, new object[] { imageXmlStr, page.PageID, ONENOTE_NAMESPACE_2010, page.PageName }); string pageChangesXml = string.Format(XML_OUTLINE, new object[] { imageXmlStr, page.PageID, ONENOTE_NAMESPACE_2010, page.PageName });
using (IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance<IOneNoteApplication>()) { using (IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance<IOneNoteApplication>()) {
LOG.InfoFormat("Sending XML: {0}", pageChangesXml); LOG.InfoFormat("Sending XML: {0}", pageChangesXml);

View file

@ -58,13 +58,11 @@ namespace GreenshotPhotobucketPlugin {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { string uploadURL = null;
string uploadURL = null; bool uploaded = plugin.Upload(captureDetails, surface, out uploadURL);
bool uploaded = plugin.Upload(captureDetails, image, out uploadURL); if (uploaded) {
if (uploaded) { exportInformation.ExportMade = true;
exportInformation.ExportMade = true; exportInformation.Uri = uploadURL;
exportInformation.Uri = uploadURL;
}
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;

View file

@ -111,10 +111,10 @@ namespace GreenshotPhotobucketPlugin {
/// Upload the capture to Photobucket /// Upload the capture to Photobucket
/// </summary> /// </summary>
/// <param name="captureDetails"></param> /// <param name="captureDetails"></param>
/// <param name="image"></param> /// <param name="surfaceToUpload">ISurface</param>
/// <param name="uploadURL">out string for the url</param> /// <param name="uploadURL">out string for the url</param>
/// <returns>true if the upload succeeded</returns> /// <returns>true if the upload succeeded</returns>
public bool Upload(ICaptureDetails captureDetails, Image image, out string uploadURL) { public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadURL) {
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);
try { try {
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
@ -123,7 +123,7 @@ namespace GreenshotPhotobucketPlugin {
// Run upload in the background // Run upload in the background
new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("photobucket", LangKey.communication_wait), new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("photobucket", LangKey.communication_wait),
delegate() { delegate() {
photobucketInfo = PhotobucketUtils.UploadToPhotobucket(image, outputSettings, captureDetails.Title, filename); photobucketInfo = PhotobucketUtils.UploadToPhotobucket(surfaceToUpload, outputSettings, captureDetails.Title, filename);
} }
); );
// This causes an exeption if the upload failed :) // This causes an exeption if the upload failed :)

View file

@ -40,9 +40,8 @@ namespace GreenshotPhotobucketPlugin {
/// Do the actual upload to Photobucket /// Do the actual upload to Photobucket
/// For more details on the available parameters, see: http://api.Photobucket.com/resources_anon /// For more details on the available parameters, see: http://api.Photobucket.com/resources_anon
/// </summary> /// </summary>
/// <param name="imageData">byte[] with image data</param>
/// <returns>PhotobucketResponse</returns> /// <returns>PhotobucketResponse</returns>
public static PhotobucketInfo UploadToPhotobucket(Image image, OutputSettings outputSettings, string title, string filename) { public static PhotobucketInfo UploadToPhotobucket(ISurface surfaceToUpload, OutputSettings outputSettings, string title, string filename) {
string responseString; string responseString;
OAuthSession oAuth = new OAuthSession(PhotobucketCredentials.ConsumerKey, PhotobucketCredentials.ConsumerSecret); OAuthSession oAuth = new OAuthSession(PhotobucketCredentials.ConsumerKey, PhotobucketCredentials.ConsumerSecret);
@ -94,7 +93,7 @@ namespace GreenshotPhotobucketPlugin {
} }
IDictionary<string, object> unsignedParameters = new Dictionary<string, object>(); IDictionary<string, object> unsignedParameters = new Dictionary<string, object>();
// Add image // Add image
unsignedParameters.Add("uploadfile", new ImageContainer(image, outputSettings, filename)); unsignedParameters.Add("uploadfile", new SurfaceContainer(surfaceToUpload, outputSettings, filename));
try { try {
string apiUrl = "http://api.photobucket.com/album/!/upload"; string apiUrl = "http://api.photobucket.com/album/!/upload";
responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, apiUrl, apiUrl.Replace("api.photobucket.com", config.SubDomain), signedParameters, unsignedParameters, null); responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, apiUrl, apiUrl.Replace("api.photobucket.com", config.SubDomain), signedParameters, unsignedParameters, null);

View file

@ -54,13 +54,11 @@ namespace GreenshotPicasaPlugin {
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
using (Image image = surface.GetImageForExport()) { string uploadURL = null;
string uploadURL = null; bool uploaded = plugin.Upload(captureDetails, surface, out uploadURL);
bool uploaded = plugin.Upload(captureDetails, image, out uploadURL); if (uploaded) {
if (uploaded) { exportInformation.ExportMade = true;
exportInformation.ExportMade = true; exportInformation.Uri = uploadURL;
exportInformation.Uri = uploadURL;
}
} }
ProcessExport(exportInformation, surface); ProcessExport(exportInformation, surface);
return exportInformation; return exportInformation;

View file

@ -109,7 +109,7 @@ namespace GreenshotPicasaPlugin {
Configure(); Configure();
} }
public bool Upload(ICaptureDetails captureDetails, Image image, out string uploadUrl) { public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) {
OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality); OutputSettings outputSettings = new OutputSettings(config.UploadFormat, config.UploadJpegQuality);
try { try {
string url = null; string url = null;
@ -117,7 +117,7 @@ namespace GreenshotPicasaPlugin {
delegate() { delegate() {
string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails));
string contentType = "image/" + config.UploadFormat.ToString(); string contentType = "image/" + config.UploadFormat.ToString();
url = PicasaUtils.UploadToPicasa(image, outputSettings, captureDetails.Title, filename); url = PicasaUtils.UploadToPicasa(surfaceToUpload, outputSettings, captureDetails.Title, filename);
} }
); );
uploadUrl = url; uploadUrl = url;

View file

@ -41,7 +41,7 @@ namespace GreenshotPicasaPlugin {
/// </summary> /// </summary>
/// <param name="imageData">byte[] with image data</param> /// <param name="imageData">byte[] with image data</param>
/// <returns>PicasaResponse</returns> /// <returns>PicasaResponse</returns>
public static string UploadToPicasa(Image imageToUpload, OutputSettings outputSettings, string title, string filename) { public static string UploadToPicasa(ISurface surfaceToUpload, OutputSettings outputSettings, string title, string filename) {
OAuthSession oAuth = new OAuthSession(PicasaCredentials.ConsumerKey, PicasaCredentials.ConsumerSecret); OAuthSession oAuth = new OAuthSession(PicasaCredentials.ConsumerKey, PicasaCredentials.ConsumerSecret);
oAuth.BrowserSize = new Size(1020, 590); oAuth.BrowserSize = new Size(1020, 590);
oAuth.AccessTokenUrl = "https://www.google.com/accounts/OAuthGetAccessToken"; oAuth.AccessTokenUrl = "https://www.google.com/accounts/OAuthGetAccessToken";
@ -67,7 +67,7 @@ namespace GreenshotPicasaPlugin {
try { try {
IDictionary<string, string> headers = new Dictionary<string, string>(); IDictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("slug", OAuthSession.UrlEncode3986(filename)); headers.Add("slug", OAuthSession.UrlEncode3986(filename));
string response = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://picasaweb.google.com/data/feed/api/user/default/albumid/default", headers, null, null, new ImageContainer(imageToUpload, outputSettings, filename)); string response = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://picasaweb.google.com/data/feed/api/user/default/albumid/default", headers, null, null, new SurfaceContainer(surfaceToUpload, outputSettings, filename));
return ParseResponse(response); return ParseResponse(response);
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Upload error: ", ex); LOG.Error("Upload error: ", ex);

View file

@ -335,10 +335,10 @@ EndSelection:<<<<<<<4
SetDataObject(ido); SetDataObject(ido);
} }
private static string getHTMLString(Image image, string filename) { private static string getHTMLString(ISurface surface, string filename) {
string utf8EncodedHTMLString = Encoding.GetEncoding(0).GetString(Encoding.UTF8.GetBytes(HTML_CLIPBOARD_STRING)); string utf8EncodedHTMLString = Encoding.GetEncoding(0).GetString(Encoding.UTF8.GetBytes(HTML_CLIPBOARD_STRING));
utf8EncodedHTMLString= utf8EncodedHTMLString.Replace("${width}", image.Width.ToString()); utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${width}", surface.Image.Width.ToString());
utf8EncodedHTMLString= utf8EncodedHTMLString.Replace("${height}", image.Height.ToString()); utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${height}", surface.Image.Height.ToString());
utf8EncodedHTMLString= utf8EncodedHTMLString.Replace("${file}", filename); utf8EncodedHTMLString= utf8EncodedHTMLString.Replace("${file}", filename);
StringBuilder sb=new StringBuilder(); StringBuilder sb=new StringBuilder();
sb.Append(utf8EncodedHTMLString); sb.Append(utf8EncodedHTMLString);
@ -349,10 +349,10 @@ EndSelection:<<<<<<<4
return sb.ToString(); return sb.ToString();
} }
private static string getHTMLDataURLString(Image image, MemoryStream pngStream) { private static string getHTMLDataURLString(ISurface surface, MemoryStream pngStream) {
string utf8EncodedHTMLString = Encoding.GetEncoding(0).GetString(Encoding.UTF8.GetBytes(HTML_CLIPBOARD_BASE64_STRING)); string utf8EncodedHTMLString = Encoding.GetEncoding(0).GetString(Encoding.UTF8.GetBytes(HTML_CLIPBOARD_BASE64_STRING));
utf8EncodedHTMLString= utf8EncodedHTMLString.Replace("${width}", image.Width.ToString()); utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${width}", surface.Image.Width.ToString());
utf8EncodedHTMLString= utf8EncodedHTMLString.Replace("${height}", image.Height.ToString()); utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${height}", surface.Image.Height.ToString());
utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${format}", "png"); utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${format}", "png");
utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(),0, (int)pngStream.Length)); utf8EncodedHTMLString = utf8EncodedHTMLString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(),0, (int)pngStream.Length));
StringBuilder sb=new StringBuilder(); StringBuilder sb=new StringBuilder();
@ -374,7 +374,7 @@ EndSelection:<<<<<<<4
/// For this problem the user should not use the direct paste (=Dib), but select Bitmap /// For this problem the user should not use the direct paste (=Dib), but select Bitmap
/// </summary> /// </summary>
private const int BITMAPFILEHEADER_LENGTH = 14; private const int BITMAPFILEHEADER_LENGTH = 14;
public static void SetClipboardData(Image image) { public static void SetClipboardData(ISurface surface) {
DataObject ido = new DataObject(); DataObject ido = new DataObject();
// This will work for Office and most other applications // This will work for Office and most other applications
@ -389,7 +389,7 @@ EndSelection:<<<<<<<4
pngStream = new MemoryStream(); pngStream = new MemoryStream();
// PNG works for Powerpoint // PNG works for Powerpoint
OutputSettings pngOutputSettings = new OutputSettings(OutputFormat.png, 100, false); OutputSettings pngOutputSettings = new OutputSettings(OutputFormat.png, 100, false);
ImageOutput.SaveToStream(image, pngStream, pngOutputSettings); ImageOutput.SaveToStream(surface, pngStream, pngOutputSettings);
pngStream.Seek(0, SeekOrigin.Begin); pngStream.Seek(0, SeekOrigin.Begin);
} }
@ -402,7 +402,7 @@ EndSelection:<<<<<<<4
bmpStream = new MemoryStream(); bmpStream = new MemoryStream();
// Save image as BMP // Save image as BMP
OutputSettings bmpOutputSettings = new OutputSettings(OutputFormat.bmp, 100, false); OutputSettings bmpOutputSettings = new OutputSettings(OutputFormat.bmp, 100, false);
ImageOutput.SaveToStream(image, bmpStream, bmpOutputSettings); ImageOutput.SaveToStream(surface, bmpStream, bmpOutputSettings);
imageStream = new MemoryStream(); imageStream = new MemoryStream();
// Copy the source, but skip the "BITMAPFILEHEADER" which has a size of 14 // Copy the source, but skip the "BITMAPFILEHEADER" which has a size of 14
@ -414,11 +414,11 @@ EndSelection:<<<<<<<4
// Set the HTML // Set the HTML
if (config.ClipboardFormats.Contains(ClipboardFormat.HTML)) { if (config.ClipboardFormats.Contains(ClipboardFormat.HTML)) {
string tmpFile = ImageOutput.SaveToTmpFile(image, new OutputSettings(OutputFormat.png), null); string tmpFile = ImageOutput.SaveToTmpFile(surface, new OutputSettings(OutputFormat.png), null);
string html = getHTMLString(image, tmpFile); string html = getHTMLString(surface, tmpFile);
ido.SetText(html, TextDataFormat.Html); ido.SetText(html, TextDataFormat.Html);
} else if (config.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL)) { } else if (config.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL)) {
string html = getHTMLDataURLString(image, pngStream); string html = getHTMLDataURLString(surface, pngStream);
ido.SetText(html, TextDataFormat.Html); ido.SetText(html, TextDataFormat.Html);
} }
} finally { } finally {

View file

@ -74,7 +74,7 @@ namespace GreenshotPlugin.Core {
/// To prevent problems with GDI version of before Windows 7: /// To prevent problems with GDI version of before Windows 7:
/// the stream is checked if it's seekable and if needed a MemoryStream as "cache" is used. /// the stream is checked if it's seekable and if needed a MemoryStream as "cache" is used.
/// </summary> /// </summary>
public static void SaveToStream(Image imageToSave, Stream stream, OutputSettings outputSettings) { public static void SaveToStream(ISurface surface, Stream stream, OutputSettings outputSettings) {
ImageFormat imageFormat = null; ImageFormat imageFormat = null;
bool disposeImage = false; bool disposeImage = false;
bool useMemoryStream = false; bool useMemoryStream = false;
@ -93,6 +93,7 @@ namespace GreenshotPlugin.Core {
case OutputFormat.tiff: case OutputFormat.tiff:
imageFormat = ImageFormat.Tiff; imageFormat = ImageFormat.Tiff;
break; break;
case OutputFormat.greenshot:
case OutputFormat.png: case OutputFormat.png:
default: default:
// Problem with non-seekable streams most likely doesn't happen with Windows 7 (OS Version 6.1 and later) // Problem with non-seekable streams most likely doesn't happen with Windows 7 (OS Version 6.1 and later)
@ -109,36 +110,52 @@ namespace GreenshotPlugin.Core {
break; break;
} }
// Removing transparency if it's not supported // check what image we want to save
if (imageFormat != ImageFormat.Png) { Image imageToSave = null;
imageToSave = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb); if (outputSettings.Format == OutputFormat.greenshot) {
// We save the image of the surface, this should not be disposed
imageToSave = surface.Image;
} else {
// We create the export image of the surface to save
imageToSave = surface.GetImageForExport();
disposeImage = true; disposeImage = true;
} }
// check for color reduction, forced or automatically
if (conf.OutputFileAutoReduceColors || outputSettings.ReduceColors) {
WuQuantizer quantizer = new WuQuantizer((Bitmap)imageToSave);
int colorCount = quantizer.GetColorCount();
LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
if (outputSettings.ReduceColors || colorCount < 256) {
try {
LOG.Info("Reducing colors on bitmap to 255.");
Image tmpImage = quantizer.GetQuantizedImage(255);
if (disposeImage) {
imageToSave.Dispose();
}
imageToSave = tmpImage;
// Make sure the "new" image is disposed
disposeImage = true;
} catch (Exception e) {
LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
}
}
} else {
LOG.Info("Skipping color reduction test, OutputFileAutoReduceColors is set to false.");
}
try { try {
// Removing transparency if it's not supported
if (imageFormat != ImageFormat.Png && Image.IsAlphaPixelFormat(imageToSave.PixelFormat)) {
Image nonAlphaImage = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb);
if (disposeImage) {
imageToSave.Dispose();
}
// Make sure the image is disposed!
disposeImage = true;
imageToSave = nonAlphaImage;
}
// check for color reduction, forced or automatically
if (conf.OutputFileAutoReduceColors || outputSettings.ReduceColors) {
WuQuantizer quantizer = new WuQuantizer((Bitmap)imageToSave);
int colorCount = quantizer.GetColorCount();
LOG.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
if (outputSettings.ReduceColors || colorCount < 256) {
try {
LOG.Info("Reducing colors on bitmap to 255.");
Image tmpImage = quantizer.GetQuantizedImage(255);
if (disposeImage) {
imageToSave.Dispose();
}
imageToSave = tmpImage;
// Make sure the "new" image is disposed
disposeImage = true;
} catch (Exception e) {
LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e);
}
}
} else {
LOG.Info("Skipping color reduction test, OutputFileAutoReduceColors is set to false.");
}
// Create meta-data // Create meta-data
PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot"); PropertyItem softwareUsedPropertyItem = CreatePropertyItem(PROPERTY_TAG_SOFTWARE_USED, "Greenshot");
if (softwareUsedPropertyItem != null) { if (softwareUsedPropertyItem != null) {
@ -172,18 +189,27 @@ namespace GreenshotPlugin.Core {
if (!foundEncoder) { if (!foundEncoder) {
throw new ApplicationException("No JPG encoder found, this should not happen."); throw new ApplicationException("No JPG encoder found, this should not happen.");
} }
} else if (imageFormat != ImageFormat.Png && Image.IsAlphaPixelFormat(imageToSave.PixelFormat)) {
// No transparency in target format
using (Bitmap tmpBitmap = ImageHelper.Clone(imageToSave, PixelFormat.Format24bppRgb)) {
tmpBitmap.Save(targetStream, imageFormat);
}
} else { } else {
imageToSave.Save(targetStream, imageFormat); imageToSave.Save(targetStream, imageFormat);
} }
// If we used a memory stream, we need to stream the memory stream to the original stream. // If we used a memory stream, we need to stream the memory stream to the original stream.
if (useMemoryStream) { if (useMemoryStream) {
memoryStream.WriteTo(stream); memoryStream.WriteTo(stream);
} }
// Output the surface elements, size and marker to the stream
if (outputSettings.Format == OutputFormat.greenshot) {
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 = System.Text.Encoding.ASCII.GetBytes(String.Format("Greenshot{0:00}.{1:00}", v.Major, v.Minor));
writer.Write(marker);
tmpStream.WriteTo(stream);
}
}
}
} finally { } finally {
if (memoryStream != null) { if (memoryStream != null) {
memoryStream.Dispose(); memoryStream.Dispose();
@ -195,36 +221,6 @@ namespace GreenshotPlugin.Core {
} }
} }
/// <summary>
/// Save a Greenshot surface
/// </summary>
/// <param name="surface">Surface to save</param>
/// <param name="fullPath">Path to file</param>
public static void SaveGreenshotSurface(ISurface surface, string fullPath) {
fullPath = FilenameHelper.MakeFQFilenameSafe(fullPath);
string path = Path.GetDirectoryName(fullPath);
// Get output settings from the configuration
OutputSettings outputSettings = new OutputSettings(OutputFormat.png);
// check whether path exists - if not create it
DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists) {
Directory.CreateDirectory(di.FullName);
}
using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) {
SaveToStream(surface.Image, stream, outputSettings);
long bytesWritten = surface.SaveElementsToStream(stream);
using (BinaryWriter writer = new BinaryWriter(stream)) {
writer.Write(bytesWritten);
Version v = Assembly.GetExecutingAssembly().GetName().Version;
string marker = String.Format("Greenshot{0:00}.{1:00}", v.Major, v.Minor);
using (StreamWriter streamWriter = new StreamWriter(stream)) {
streamWriter.Write(marker);
}
}
}
}
/// <summary> /// <summary>
/// Load a Greenshot surface /// Load a Greenshot surface
/// </summary> /// </summary>
@ -274,46 +270,6 @@ namespace GreenshotPlugin.Core {
return returnSurface; return returnSurface;
} }
/// <summary>
/// Saves image to specific path with specified quality
/// </summary>
public static void Save(Image image, string fullPath, bool allowOverwrite, OutputSettings outputSettings, bool copyPathToClipboard) {
fullPath = FilenameHelper.MakeFQFilenameSafe(fullPath);
string path = Path.GetDirectoryName(fullPath);
// check whether path exists - if not create it
DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists) {
Directory.CreateDirectory(di.FullName);
}
string extension = Path.GetExtension(fullPath);
if (extension != null && extension.StartsWith(".")) {
extension = extension.Substring(1);
}
OutputFormat format = OutputFormat.png;
try {
if (extension != null) {
format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower());
}
} catch (ArgumentException ae) {
LOG.Warn("Couldn't parse extension: " + extension, ae);
}
if (!allowOverwrite && File.Exists(fullPath)) {
ArgumentException throwingException = new ArgumentException("File '" + fullPath + "' already exists.");
throwingException.Data.Add("fullPath", fullPath);
throw throwingException;
}
LOG.DebugFormat("Saving image to {0}", fullPath);
// Create the stream and call SaveToStream
using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) {
SaveToStream(image, stream, outputSettings);
}
if (copyPathToClipboard) {
ClipboardHelper.SetClipboardData(fullPath);
}
}
/// <summary> /// <summary>
/// Saves image to specific path with specified quality /// Saves image to specific path with specified quality
/// </summary> /// </summary>
@ -332,16 +288,10 @@ namespace GreenshotPlugin.Core {
throwingException.Data.Add("fullPath", fullPath); throwingException.Data.Add("fullPath", fullPath);
throw throwingException; throw throwingException;
} }
LOG.DebugFormat("Saving image to {0}", fullPath); LOG.DebugFormat("Saving surface to {0}", fullPath);
// Create the stream and call SaveToStream // Create the stream and call SaveToStream
if (outputSettings.Format == OutputFormat.greenshot) { using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) {
SaveGreenshotSurface(surface, fullPath); SaveToStream(surface, stream, outputSettings);
} else {
using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) {
using (Image image = surface.GetImageForExport()) {
SaveToStream(image, stream, outputSettings);
}
}
} }
if (copyPathToClipboard) { if (copyPathToClipboard) {
@ -367,23 +317,6 @@ namespace GreenshotPlugin.Core {
} }
return format; return format;
} }
/// <summary>
/// saves img to fullpath
/// </summary>
/// <param name="img">the image to save</param>
/// <param name="fullPath">the absolute destination path including file name</param>
/// <param name="allowOverwrite">true if overwrite is allowed, false if not</param>
public static void Save(Image img, string fullPath, bool allowOverwrite) {
OutputFormat format = FormatForFilename(fullPath);
// Get output settings from the configuration
OutputSettings outputSettings = new OutputSettings(format);
if (conf.OutputFilePromptQuality) {
QualityDialog qualityDialog = new QualityDialog(outputSettings);
qualityDialog.ShowDialog();
}
Save(img, fullPath, allowOverwrite, outputSettings, conf.OutputFileCopyPathToClipboard);
}
#endregion #endregion
#region save-as #region save-as
@ -460,7 +393,7 @@ namespace GreenshotPlugin.Core {
/// </summary> /// </summary>
/// <param name="image"></param> /// <param name="image"></param>
/// <returns></returns> /// <returns></returns>
public static string SaveToTmpFile(Image image, OutputSettings outputSettings, string destinationPath) { public static string SaveToTmpFile(ISurface surface, OutputSettings outputSettings, string destinationPath) {
string tmpFile = Path.GetRandomFileName() + "." + outputSettings.Format.ToString(); string tmpFile = Path.GetRandomFileName() + "." + outputSettings.Format.ToString();
// Prevent problems with "other characters", which could cause problems // Prevent problems with "other characters", which could cause problems
tmpFile = Regex.Replace(tmpFile, @"[^\d\w\.]", ""); tmpFile = Regex.Replace(tmpFile, @"[^\d\w\.]", "");
@ -471,7 +404,7 @@ namespace GreenshotPlugin.Core {
LOG.Debug("Creating TMP File : " + tmpPath); LOG.Debug("Creating TMP File : " + tmpPath);
try { try {
ImageOutput.Save(image, tmpPath, true, outputSettings, false); ImageOutput.Save(surface, tmpPath, true, outputSettings, false);
tmpFileCache.Add(tmpPath, tmpPath); tmpFileCache.Add(tmpPath, tmpPath);
} catch (Exception) { } catch (Exception) {
return null; return null;

View file

@ -413,13 +413,13 @@ namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// A container to supply images to a Multi-part form data upload /// A container to supply images to a Multi-part form data upload
/// </summary> /// </summary>
public class ImageContainer : IBinaryContainer { public class SurfaceContainer : IBinaryContainer {
private Image image; private ISurface surface;
private OutputSettings outputSettings; private OutputSettings outputSettings;
private string fileName; private string fileName;
public ImageContainer(Image image, OutputSettings outputSettings, string filename) { public SurfaceContainer(ISurface surface, OutputSettings outputSettings, string filename) {
this.image = image; this.surface = surface;
this.outputSettings = outputSettings; this.outputSettings = outputSettings;
this.fileName = filename; this.fileName = filename;
} }
@ -431,7 +431,7 @@ namespace GreenshotPlugin.Core {
/// <returns>string</returns> /// <returns>string</returns>
public string ToBase64String(Base64FormattingOptions formattingOptions) { public string ToBase64String(Base64FormattingOptions formattingOptions) {
using (MemoryStream stream = new MemoryStream()) { using (MemoryStream stream = new MemoryStream()) {
ImageOutput.SaveToStream(image, stream, outputSettings); ImageOutput.SaveToStream(surface, stream, outputSettings);
return System.Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions); return System.Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions);
} }
} }
@ -443,7 +443,7 @@ namespace GreenshotPlugin.Core {
/// <returns>byte[]</returns> /// <returns>byte[]</returns>
public byte[] ToByteArray() { public byte[] ToByteArray() {
using (MemoryStream stream = new MemoryStream()) { using (MemoryStream stream = new MemoryStream()) {
ImageOutput.SaveToStream(image, stream, outputSettings); ImageOutput.SaveToStream(surface, stream, outputSettings);
return stream.ToArray(); return stream.ToArray();
} }
} }
@ -462,7 +462,7 @@ namespace GreenshotPlugin.Core {
"image/" + outputSettings.Format.ToString()); "image/" + outputSettings.Format.ToString());
formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header));
ImageOutput.SaveToStream(image, formDataStream, outputSettings); ImageOutput.SaveToStream(surface, formDataStream, outputSettings);
} }
/// <summary> /// <summary>
@ -471,7 +471,7 @@ namespace GreenshotPlugin.Core {
/// <param name="dataStream"></param> /// <param name="dataStream"></param>
public void WriteToStream(Stream dataStream) { public void WriteToStream(Stream dataStream) {
// Write the file data directly to the Stream, rather than serializing it to a string. // Write the file data directly to the Stream, rather than serializing it to a string.
ImageOutput.SaveToStream(image, dataStream, outputSettings); ImageOutput.SaveToStream(surface, dataStream, outputSettings);
} }
/// <summary> /// <summary>