public void Execute(Attachment file, ImageMeta meta, NameValueCollection Parameters, Driver driver, string savedName, AttachmentUploadHandler handler) { file.file_size = file.RawData.Count; file.modify_time = DateTime.UtcNow; file.url = "/v2/attachments/view/?object_id=" + file.object_id; file.saved_file_name = savedName; file.Upload(meta, Parameters["apikey"], Parameters["session_token"]); new FileStorage(driver).SaveAttachment(file); BsonDocument dbDoc = CreateDbDocument(file, meta, savedName); BsonDocument existDoc = AttachmentCollection.Instance.FindOneAs <BsonDocument>( new QueryDocument("_id", file.object_id)); if (existDoc != null) { existDoc.DeepMerge(dbDoc); AttachmentCollection.Instance.Save(existDoc); } else { AttachmentCollection.Instance.Save(dbDoc); } AttachmentEventArgs aEvtArgs = new AttachmentEventArgs { Attachment = file, Driver = driver }; handler.OnAttachmentSaved(aEvtArgs); HttpHelper.RespondSuccess(handler.Response, ObjectUploadResponse.CreateSuccess(file.object_id)); }
protected override BsonDocument CreateDbDocument(Attachment file, ImageMeta meta, string savedName) { using (Bitmap img = new Bitmap(new MemoryStream(file.RawData.Array, file.RawData.Offset, file.RawData.Count))) { Attachment thumbnailAttachment = new Attachment(file); thumbnailAttachment.image_meta = new ImageProperty(); thumbnailAttachment.image_meta.SetThumbnailInfo(meta, new ThumbnailInfo { mime_type = file.mime_type, modify_time = DateTime.UtcNow, url = file.url + "&image_meta=" + meta.ToString().ToLower(), file_size = file.file_size, file_name = savedName, width = img.Width, height = img.Height, saved_file_name = savedName }); thumbnailAttachment.mime_type = null; thumbnailAttachment.modify_time = DateTime.UtcNow; thumbnailAttachment.url = null; thumbnailAttachment.file_size = 0; return(thumbnailAttachment.ToBsonDocument()); } }
public static ObjectUploadResponse UploadImage(string url, ArraySegment <byte> imageData, string groupId, string objectId, string fileName, string contentType, ImageMeta meta, string apiKey, string token) { return(Upload(url, imageData, groupId, objectId, fileName, contentType, meta, AttachmentType.image, apiKey, token)); }
public ObjectUploadResponse Upload(ImageMeta meta, string apiKey, string sessionToken) { string url = CloudServer.BaseUrl + "attachments/upload/"; return(Upload(url, rawData, group_id, object_id, file_name, mime_type, meta, type, apiKey, sessionToken)); }
public TempCoverHandle( ILogger <ImageService> logger, Func <string, string> getCoverFqfn, ImageMeta meta) { _getCoverFqfn = getCoverFqfn; _logger = logger; Meta = meta; }
public void Render(Graphics g, ImageMeta image) { decimal zoom = _control.Zoom; int w, h; bool isRotated = false; bool useOptimizedImage = false; if ((_control.Rotation == 0) || (_control.Rotation == 180)) { w = image.ActualWidth; h = image.ActualHeight; } else { w = image.ActualHeight; h = image.ActualWidth; isRotated = true; } if (zoom == 0) { // "Best fit" if ((w < _control.Width) && (h < _control.Height)) { zoom = 1; } else { decimal propW = (decimal)_control.Width / (decimal)w; decimal propH = (decimal)_control.Height / (decimal)h; zoom = Math.Min(propW, propH); useOptimizedImage = true; } } int newWidth = (int)((decimal)image.ActualWidth * zoom); int newHeight = (int)((decimal)image.ActualHeight * zoom); Bitmap imageToPaint = image.Image; if (useOptimizedImage) { imageToPaint = GetOptimizedImage(image, isRotated, newWidth, newHeight); } if (imageToPaint != null) { g.TranslateTransform(_control.Width / 2, _control.Height / 2); g.TranslateTransform(_control.Pan.X, _control.Pan.Y); g.RotateTransform(_control.Rotation); g.TranslateTransform(-(newWidth / 2), -(newHeight / 2)); g.DrawImage(imageToPaint, 0, 0, newWidth, newHeight); g.ResetTransform(); } }
private Bitmap GetOptimizedImage(ImageMeta image, bool isRotated, int newWidth, int newHeight) { if ((_optimizedImageFileName != image.FileName) || (_optimizedImageRotation != _control.Rotation)) { InvalidateCache(); _optimizedScreenSizeImage = new Bitmap(image.Image, newWidth, newHeight); _optimizedImageFileName = image.FileName; _optimizedImageRotation = _control.Rotation; } return(_optimizedScreenSizeImage); }
private void UpstreamThumbnail(ThumbnailInfo thumbnail, string groupId, string fullImgId, ImageMeta meta, string apiKey, string token) { using (MemoryStream output = new MemoryStream()) { Attachment.UploadImage(new ArraySegment <byte>(thumbnail.RawData), groupId, fullImgId, thumbnail.file_name, "image/jpeg", meta, apiKey, token); OnThumbnailUpstreamed(new ThumbnailUpstreamedEventArgs(thumbnail.RawData.Length)); logger.DebugFormat("Thumbnail {0} is uploaded to Cloud", thumbnail.file_name); } }
private ArtFile GetTestArtFile() { ArtFile artFile = new ArtFile(); artFile.palettes.Add(new Palette()); ImageMeta imageMeta = new ImageMeta(); imageMeta.width = 10; imageMeta.scanLineByteWidth = 12; imageMeta.paletteIndex = 0; artFile.imageMetas.Add(imageMeta); return(artFile); }
public static ThumbnailInfo MakeThumbnail(Bitmap origin, ImageMeta meta, ExifOrientations orientation, string attachmentId, Driver driver, string origFileName) { Bitmap thumbnail = null; if (meta == ImageMeta.Square) { thumbnail = MakeSquareThumbnail(origin); } else { thumbnail = ImageHelper.ScaleBasedOnLongSide(origin, (int)meta); } try { if (orientation != ExifOrientations.Unknown) { ImageHelper.CorrectOrientation(orientation, thumbnail); } else { ImageHelper.CorrectOrientation(ImageHelper.ImageOrientation(origin), thumbnail); } } catch (System.Runtime.InteropServices.ExternalException ex) { logger.ErrorFormat("Unable to correct orientation of image {0}", origFileName); logger.Error("External exception", ex); } ImageSaveStrategy imageStrategy = GetImageSaveStrategy(Path.GetExtension(origFileName)); SavedResult savedThumbnail = imageStrategy.Save(thumbnail, attachmentId, meta, driver); return(new ThumbnailInfo { saved_file_name = savedThumbnail.FileName, file_name = origFileName, width = thumbnail.Width, height = thumbnail.Height, file_size = savedThumbnail.SavedRawData.Length, mime_type = savedThumbnail.MimeType, modify_time = DateTime.UtcNow, url = "/v2/attachments/view/?object_id=" + attachmentId + "&image_meta=" + meta.ToString().ToLower(), RawData = savedThumbnail.SavedRawData }); }
private void SaveAttachmentInfoToDB(Attachment file, ImageMeta meta, string savedName) { BsonDocument dbDoc = CreateDbDocument(file, meta, savedName); BsonDocument existDoc = AttachmentCollection.Instance.FindOneAs <BsonDocument>( new QueryDocument("_id", file.object_id)); if (existDoc != null) { existDoc.DeepMerge(dbDoc); AttachmentCollection.Instance.Save(existDoc); } else { AttachmentCollection.Instance.Save(dbDoc); } }
protected override void HandleRequest() { Attachment file = GetFileFromMultiPartData(); ImageMeta meta = GetImageMeta(); bool isNewOrigImage = file.object_id == null && meta == ImageMeta.Origin; if (file.object_id == null) { file.object_id = Guid.NewGuid().ToString(); } if (Parameters["apikey"] == null || Parameters["session_token"] == null) { throw new FormatException("apikey or session_token is missing"); } Driver driver = DriverCollection.Instance.FindOne(Query.ElemMatch("groups", Query.EQ("group_id", file.group_id))); if (driver == null) { throw new FormatException("group_id is not assocaited with a registered user"); } string savedName = GetSavedFilename(file, meta); FileStorage storage = new FileStorage(driver); IAttachmentUploadStrategy handleStrategy = GetHandleStrategy(file, isNewOrigImage, meta); handleStrategy.Execute(file, meta, Parameters, driver, savedName, this); //Larry 2012/03/12, Enqueue upload original photo process if (!driver.isPrimaryStation && ((handleStrategy is NewOriginalImageUploadStrategy) || (handleStrategy is OldOriginImageUploadStrategy))) { TaskQueue.EnqueueLow((state) => { file.Upload(ImageMeta.Origin, Parameters["apikey"], Parameters["session_token"]); }); } long newValue = System.Threading.Interlocked.Add(ref g_counter, 1); if (newValue % 5 == 0) { GC.Collect(); } }
public SavedResult Save(Bitmap img, string attchId, ImageMeta meta, Driver driver) { using (MemoryStream m = new MemoryStream()) { img.Save(m, ImageFormat.Png); SavedResult savedResult = new SavedResult { SavedRawData = m.ToArray(), FileName = string.Format("{0}_{1}.png", attchId, meta.ToString().ToLower()), MimeType = "image/png" }; new FileStorage(driver).SaveFile(savedResult.FileName, new ArraySegment <byte>(savedResult.SavedRawData)); return(savedResult); } }
public static async Task <Color[]> ImageMetaRT(IRandomAccessStream imageStream, int metaCount, int maxError) { var colors = new Color[metaCount]; var imgDecoder = await BitmapDecoder.CreateAsync(imageStream); var imgProvider = await imgDecoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); var imageBytes = imgProvider.DetachPixelData(); var colorsInt = ImageMeta.meta_calculate(imageBytes, metaCount, maxError); for (byte index = 0; index < metaCount; index++) { colors[index] = ColorConvert(colorsInt[index]); } return(colors); }
public async Task <ITempCoverHandle> SaveCroppedCover(Stream stream, CropRectangle?crop = null) { var(image, format) = await Image.LoadWithFormatAsync(stream); var resize = new ResizeOptions { Size = new Size(AppConfig.Cover.Width, AppConfig.Cover.Width), Mode = ResizeMode.Max, }; if (crop != null) { image.Mutate(x => x .AutoOrient() .Crop(new Rectangle(crop.X, crop.Y, crop.Width, crop.Height)) .Resize(resize)); } else { image.Mutate(x => x .AutoOrient() .Resize(resize)); } var imageId = await Nanoid.Nanoid.GenerateAsync("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); var fileName = $"{imageId}.{format.FileExtensions.First()}"; var imageFqfn = GetCoverFqfn(fileName); var baseDir = Path.GetDirectoryName(imageFqfn); if (baseDir != null && !Directory.Exists(baseDir)) { Directory.CreateDirectory(baseDir); } await using var outFile = new FileStream(imageFqfn, FileMode.OpenOrCreate, FileAccess.Write); await image.SaveAsync(outFile, format); var meta = new ImageMeta(fileName, image.Width, image.Height, outFile.Length); return(new TempCoverHandle(_logger, GetCoverFqfn, meta)); }
public ThumbnailInfo GetThumbnailInfo(ImageMeta meta) { switch (meta) { case ImageMeta.Small: return(small); case ImageMeta.Medium: return(medium); case ImageMeta.Large: return(large); case ImageMeta.Square: return(square); default: throw new ArgumentException("meta is not a thumbnail: " + meta); } }
public SavedResult Save(Bitmap img, string attchId, ImageMeta meta, Driver driver) { using (MemoryStream m = new MemoryStream()) { EncoderParameters encodeParams = new EncoderParameters(1); encodeParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)85); img.Save(m, ImageHelper.JpegCodec, encodeParams); SavedResult savedResult = new SavedResult { SavedRawData = m.ToArray(), FileName = string.Format("{0}_{1}.jpeg", attchId, meta.ToString().ToLower()), MimeType = "image/jpeg" }; new FileStorage(driver).SaveFile(savedResult.FileName, new ArraySegment <byte>(savedResult.SavedRawData)); return(savedResult); } }
private static string GetSavedFilename(Attachment file, ImageMeta meta) { string name = file.object_id; if (meta != ImageMeta.Origin && meta != ImageMeta.None) { name += "_" + meta.ToString().ToLower(); } string originalSuffix = Path.GetExtension(file.file_name); if (originalSuffix != null) { return(name + originalSuffix); } else { return(name); } }
public static ObjectUploadResponse Upload(string url, ArraySegment <byte> imageData, string groupId, string objectId, string fileName, string contentType, ImageMeta meta, AttachmentType type, string apiKey, string token) { try { Dictionary <string, object> pars = new Dictionary <string, object>(); pars["type"] = type.ToString(); if (meta != ImageMeta.None) { pars["image_meta"] = meta.ToString().ToLower(); } pars["session_token"] = token; pars["apikey"] = apiKey; if (objectId != null) { pars["object_id"] = objectId; } pars["group_id"] = groupId; HttpWebResponse _webResponse = Waveface.MultipartFormDataPostHelper.MultipartFormDataPost( url, "Mozilla 4.0+", pars, fileName, contentType, imageData); using (StreamReader reader = new StreamReader(_webResponse.GetResponseStream())) { return(fastJSON.JSON.Instance.ToObject <ObjectUploadResponse>(reader.ReadToEnd())); } } catch (WebException e) { throw new WammerCloudException("Wammer cloud error", e); } }
public void Execute(Attachment file, ImageMeta meta, NameValueCollection Parameters, Driver driver, string savedName, AttachmentUploadHandler handler) { this.handler = handler; this.driver = driver; file.file_size = file.RawData.Count; file.modify_time = DateTime.UtcNow; file.url = "/v2/attachments/view/?object_id=" + file.object_id; file.saved_file_name = savedName; BeforeSaveAttachment(file, Parameters, meta); new FileStorage(driver).SaveFile(savedName, file.RawData); SaveAttachmentInfoToDB(file, meta, savedName); AttachmentEventArgs aEvtArgs = new AttachmentEventArgs { Attachment = file, Driver = driver }; ImageAttachmentEventArgs evtArgs = new ImageAttachmentEventArgs { Attachment = file, Meta = meta, UserApiKey = Parameters["apikey"], UserSessionToken = Parameters["session_token"], Driver = driver }; handler.OnAttachmentSaved(aEvtArgs); handler.OnImageAttachmentSaved(evtArgs); HttpHelper.RespondSuccess(handler.Response, ObjectUploadResponse.CreateSuccess(file.object_id)); handler.OnImageAttachmentCompleted(evtArgs); }
public void SetThumbnailInfo(ImageMeta meta, ThumbnailInfo thumbnail) { switch (meta) { case ImageMeta.Small: small = thumbnail; break; case ImageMeta.Medium: medium = thumbnail; break; case ImageMeta.Large: large = thumbnail; break; case ImageMeta.Square: square = thumbnail; break; default: throw new ArgumentException("meta is not a thumbnail: " + meta); } }
private static BsonDocument CreateDbDocument(Attachment file, ImageMeta meta, string savedName) { return(file.ToBsonDocument()); }
protected override void HandleRequest() { ImageMeta imageMeta = ImageMeta.None; try { string objectId = Parameters["object_id"]; if (objectId == null) { throw new ArgumentException("missing required param: object_id"); } if (Parameters["image_meta"] == null) { imageMeta = ImageMeta.Origin; } else { imageMeta = (ImageMeta)Enum.Parse(typeof(ImageMeta), Parameters["image_meta"], true); } // "target" parameter is used to request cover image or slide page. // In this version station has no such resources so station always forward this // request to cloud. if (Parameters["target"] != null) { throw new FileNotFoundException(); } string namePart = objectId; string metaStr = ""; if (imageMeta != ImageMeta.Origin) { metaStr = imageMeta.ToString().ToLower(); namePart += "_" + metaStr; } Attachment doc = AttachmentCollection.Instance.FindOne(Query.EQ("_id", objectId)); if (doc == null) { throw new FileNotFoundException(); } Driver driver = DriverCollection.Instance.FindOne(Query.ElemMatch("groups", Query.EQ("group_id", doc.group_id))); FileStorage storage = new FileStorage(driver); FileStream fs = storage.LoadByNameWithNoSuffix(namePart); Response.StatusCode = 200; Response.ContentLength64 = fs.Length; Response.ContentType = doc.mime_type; if (doc.type == AttachmentType.image && imageMeta != ImageMeta.Origin) { Response.ContentType = doc.image_meta.GetThumbnailInfo(imageMeta).mime_type; } Wammer.Utility.StreamHelper.BeginCopy(fs, Response.OutputStream, CopyComplete, new CopyState(fs, Response, objectId)); } catch (ArgumentException e) { logger.Warn("Bad request: " + e.Message); HttpHelper.RespondFailure(Response, e, (int)HttpStatusCode.BadRequest); } catch (FileNotFoundException) { TunnelToCloud(AdditionalParam); } }
private static IAttachmentUploadStrategy GetHandleStrategy(Attachment file, bool isNewOrigImage, ImageMeta meta) { if (isNewOrigImage) { return(new NewOriginalImageUploadStrategy()); } else if (file.type == AttachmentType.doc) { return(new DocumentUploadStrategy()); } else if (file.type == AttachmentType.image && meta != ImageMeta.Origin) { return(new ImageThumbnailUploadStrategy()); } else { return(new OldOriginImageUploadStrategy()); } }
protected override void BeforeSaveAttachment(Attachment file, NameValueCollection Parameters, ImageMeta meta) { file.saved_file_name = null; // this is thumbnail, so don't modify saved_file_name of original image file.Upload(meta, Parameters["apikey"], Parameters["session_token"]); }
virtual protected void BeforeSaveAttachment(Attachment file, NameValueCollection Parameters, ImageMeta meta) { }
abstract protected BsonDocument CreateDbDocument(Attachment file, ImageMeta meta, string savedName);
protected override BsonDocument CreateDbDocument(Attachment file, ImageMeta meta, string savedName) { return(file.ToBsonDocument()); }
protected override void BeforeSaveAttachment(Attachment file, NameValueCollection Parameters, ImageMeta meta) { // Upload to cloud and then save to local to ensure cloud post API // can process post with attachments correctly. // In the future when station is able to handle post and sync data with cloud // this step is not necessary int imgWidth, imgHeight; ThumbnailInfo medium; using (Bitmap imageBitmap = new Bitmap(new MemoryStream(file.RawData.Array, file.RawData.Offset, file.RawData.Count))) { imgWidth = imageBitmap.Width; imgHeight = imageBitmap.Height; file.Orientation = ImageHelper.ImageOrientation(imageBitmap); medium = ImagePostProcessing.MakeThumbnail( imageBitmap, ImageMeta.Medium, file.Orientation, file.object_id, driver, file.file_name); } Attachment thumb = new Attachment(file); thumb.RawData = new ArraySegment <byte>(medium.RawData); thumb.file_size = medium.file_size; thumb.mime_type = medium.mime_type; thumb.Upload(ImageMeta.Medium, Parameters["apikey"], Parameters["session_token"]); handler.OnThumbnailUpstreamed(new ThumbnailUpstreamedEventArgs(thumb.file_size)); file.image_meta = new ImageProperty { medium = medium, width = imgWidth, height = imgHeight }; }
public static ObjectUploadResponse UploadImage(ArraySegment <byte> imageData, string group_id, string objectId, string fileName, string contentType, ImageMeta meta, string apikey, string token) { string url = CloudServer.BaseUrl + "attachments/upload/"; return(UploadImage(url, imageData, group_id, objectId, fileName, contentType, meta, apikey, token)); }