void Start() { m_Thumbs = new List<Thumbnail>(); #if UNITY_EDITOR for (int o = 0; o < 2; o++ ) { for ( int i = 0; i < 6; ++i ) { Thumbnail temp = new Thumbnail( Resources.Load( "Textures/Photosphere00" + i ) as Texture2D, "Textures/Photosphere00" + i, Country(), Date() ); m_Thumbs.Add( temp ); } } #elif UNITY_ANDROID m_Textures = m_JUInterface.GetImagePaths(); foreach ( string file in m_Textures ) { if ( m_JUInterface.DecodeImage( file ) ) m_Thumbs.Add( new Thumbnail( m_JUInterface.Image, file, m_JUInterface.Width, m_JUInterface.Height, m_JUInterface.Date, m_JUInterface.Country ) ); } #elif UNITY_IOS m_Textures = m_IUInterface.GetImages(); foreach (string file in m_Textures ) { m_Thumbs.Add( new Thumbnail( iOSUnityInterface.GetPanoramaData( file ), file, m_IUInterface.GetWidth( file ), m_IUInterface.GetHeight( file ), m_IUInterface.GetDate( file ), m_IUInterface.GetCountry( file ) ) ); } #endif }
public bool Create(Thumbnail thumb) { dbContext.Thumbnails.Add(thumb); int result = dbContext.SaveChanges(); return (result > 0); }
/// <summary> /// Create a new window /// </summary> /// <param name="handler">window handler(unieke key)</param> public Window(IntPtr handler) { this.Handler = handler; Title=GetTitle(); SetIcon(); Thumbnail = new Thumbnail(handler); var tilteThread = new Thread(CheckTitle); tilteThread.Start(); }
public async Task<IActionResult> Thumbnail(Thumbnail.Query query) { var model = await _mediator.SendAsync(query); if (model == null) { return NotFound(); } return File(model.FileContents, model.ContentType); }
protected void Page_Load(object sender, EventArgs e) { // System.Drawing.Image thumbnail_image = null;//缩略图 System.Drawing.Image original_image = null;//原图 System.Drawing.Bitmap final_image = null;//最终图片 System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { // Get the data HttpPostedFile jpeg_image_upload = Request.Files["Filedata"]; // Retrieve the uploaded image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); int width = original_image.Width; int height = original_image.Height; final_image = new System.Drawing.Bitmap(original_image); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.DrawImage(original_image, 0, 0, width, height); ms = new MemoryStream(); final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer()); List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>; if (thumbnails == null) { thumbnails = new List<Thumbnail>(); Session["file_info"] = thumbnails; } thumbnails.Add(thumb); Response.StatusCode = 200; Response.Write(thumbnail_id); } catch (Exception ex) { Response.StatusCode = 500; Response.Write("An error occured"); Response.End(); } finally { // Clean up if (final_image != null) final_image.Dispose(); if (graphic != null) graphic.Dispose(); if (ms != null) ms.Close(); Response.End(); } }
public static Thumbnail Instance() { if (!instance) { instance = FindObjectOfType(typeof(Thumbnail)) as Thumbnail; if (!instance) Debug.LogError("There needs to be one active Thumbnail script on a GameObject in your scene."); instance.gameObject.SetActive(false); } return instance; }
public void AddThumbnail (string path, Pixbuf pixbuf) { Thumbnail thumbnail = new Thumbnail (); thumbnail.path = path; thumbnail.pixbuf = pixbuf; RemoveThumbnailForPath (path); pixbuf_mru.Insert (0, thumbnail); pixbuf_hash.Add (path, thumbnail); MaybeExpunge (); }
public void AddThumbnail(Uri uri, Pixbuf pixbuf) { Thumbnail thumbnail = new Thumbnail (); thumbnail.uri = uri; thumbnail.pixbuf = pixbuf; RemoveThumbnailForUri (uri); pixbuf_mru.Insert (0, thumbnail); pixbuf_hash.Add (uri, thumbnail); MaybeExpunge (); }
private void InstantiateThumbnails() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 4; j++) { Vector3 instantiationPosition = new Vector3( 0, size.y / 2f * -i - size.y / 4f, size.z / 4f * -j - size.z / 8f); GameObject thumbnailObj = Instantiate(WindowResources.Instance.Thumbnail, startPosition.transform); thumbnailObj.transform.localPosition = instantiationPosition; thumbnailObj.transform.localScale = new Vector3(9, 9, 9); Thumbnail thumbnailScript = thumbnailObj.GetComponent <Thumbnail>(); thumbnailScript.InstantiationParent = this; thumbnailScript.Visible = false; thumbnails.Add(thumbnailScript); } } }
/// <summary> /// Cập nhật hình ảnh không có mã SKU /// </summary> /// <param name="productID"></param> /// <param name="uploadedFile"></param> /// <returns>File Name</returns> private string _uploadImageClean(int productID, UploadedFile uploadedFile) { // Upload image var folder = Server.MapPath("/uploads/images"); var fileName = Slug.ConvertToSlug(Path.GetFileName(uploadedFile.FileName), isFile: true); var filePath = String.Format("{0}/{1}-clean-{2}", folder, productID, fileName); if (File.Exists(filePath)) { filePath = String.Format("{0}/{1}-clean-{2}-{3}", folder, productID, DateTime.UtcNow.ToString("HHmmssffff"), fileName); } uploadedFile.SaveAs(filePath); // Thumbnail Thumbnail.create(filePath, 85, 113); Thumbnail.create(filePath, 159, 212); Thumbnail.create(filePath, 240, 320); Thumbnail.create(filePath, 350, 467); Thumbnail.create(filePath, 600, 0); return(Path.GetFileName(filePath)); }
public override MixPage ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { GenerateSEO(_context, _transaction); EditorValue ??= Content; EditorType ??= MixEditorType.Html; Template = View != null ? $"{View.FolderType}/{View.FileName}{View.Extension}" : Template; Layout = Master != null ? $"{Master.FolderType}/{Master.FileName}{Master.Extension}" : null; if (Id == 0) { Id = Repository.Max(c => c.Id, _context, _transaction).Data + 1; CreatedDateTime = DateTime.UtcNow; } LastModified = DateTime.UtcNow; if (!string.IsNullOrEmpty(Image) && Image[0] == '/') { Image = Image.Substring(1); } if (!string.IsNullOrEmpty(Thumbnail) && Thumbnail[0] == '/') { Thumbnail = Thumbnail.Substring(1); } return(base.ParseModel(_context, _transaction)); }
private static ProductGetOut _getProduct(tbl_Product product) { var quantity = StockManagerController.getQuantityStock2BySKU(product.ProductSKU); var result = new ProductGetOut() { ID = product.ID, ProductName = product.ProductTitle, ProductVariable = String.Empty, ProductVariableName = String.Empty, ProductVariableValue = String.Empty, ProductStyle = 1, ProductImage = Thumbnail.getURL(product.ProductImage, Thumbnail.Size.Normal), ProductImageOrigin = Thumbnail.getURL(product.ProductImage, Thumbnail.Size.Source), SKU = product.ProductSKU.Trim().ToUpper(), SupplierID = product.SupplierID.HasValue ? product.SupplierID.Value : 0, SupplierName = String.IsNullOrEmpty(product.SupplierName) ? String.Empty : product.SupplierName, WarehouseQuantity = string.Format("{0:N0}", quantity), ParentID = product.ID, ParentSKU = product.ProductSKU }; return(result); }
protected override void PopulateTemplate() { base.PopulateTemplate(); string thumbnail = Thumbnail.PathForUri(BU.StringFu.PathToQuotedFileUri(Hit.Uri.LocalPath), ThumbnailSize.Normal); if (File.Exists(thumbnail)) { Template ["Thumbnail"] = Images.GetHtmlSource(thumbnail, Hit.MimeType); } else { Template ["Thumbnail"] = Images.GetHtmlSource(Hit.Uri.LocalPath, Hit.MimeType); } // F-Spot hacks string [] properties = Hit.GetProperties("fspot:Tag"); if (properties != null) { Template ["Tags"] += String.Join(" / ", properties); } }
private void UpdateDetails() { detailsNameText.text = selectedCitizen.name; detailsImage.sprite = Thumbnail.Generate(selectedCitizen.transform); var skills = selectedCitizen.skills.GetAll(); for (int i = 0; i < Mathf.Max(skills.Count, skillList.childCount); i++) { if (i < skills.Count && i < skillList.childCount) { skillList.GetChild(i).gameObject.SetActive(true); skillList.GetChild(i).GetChild(0).GetComponent <TextMeshProUGUI>().text = skills[i].name.ToString(); skillList.GetChild(i).GetChild(1).GetComponent <Slider>().value = skills[i].value; } else { skillList.GetChild(i).gameObject.SetActive(false); } } UpdateWorkplacePanel(); }
private async void StartFetching() { var ctx = new ReduxEntities(); var thumbnail = new Thumbnail(); thumbnail.Show(); while (IsCancelled == false) { var nextSixteen = (from item in ctx.scan_pips_contributors where item.scanned == false select item).Take(16).ToList(); if (nextSixteen.Count == 0) { IsCancelled = true; } else { await TaskEx.WhenAll(from item in nextSixteen select FetchItemGenreAndIonAsync(item, thumbnail, this, IsTags, IsIonContributors, IsCategories)); ctx.SaveChanges(); } } IsRunning = false; IsCancelled = false; }
public static void CreateThumbnail(string pic, string path, string filename) { if (string.IsNullOrEmpty(Configinfo.ThumbnailInfo.Trim())) { return; } foreach (var s in Configinfo.ThumbnailInfo.Split(new[] { ',' })) { var ss = s.Split(new[] { 'x' }); if (ss.Length != 2) { continue; } var w = Utils.StrToInt(ss[0]); var h = Utils.StrToInt(ss[1]); if (w <= 0 || h <= 0) { continue; } CreateFolder(HttpContext.Current.Server.MapPath(path + s + "/")); Thumbnail.MakeThumbnailImage(HttpContext.Current.Server.MapPath(pic), HttpContext.Current.Server.MapPath(path + s + "/") + filename, w, h); } }
private async void PlaybackMovie(Thumbnail content) { ChangeProgressText(SystemUtil.GetStringResource("Progress_OpeningMovieStream")); UpdateInnerState(ViewerState.MoviePlayback); try { MoviePlayer.Visibility = Visibility.Visible; UpdateAppBarColor(); await Operator.PlaybackMovie(content); } catch (Exception e) { DebugUtil.Log(() => e.StackTrace); MoviePlayer.Visibility = Visibility.Collapsed; UpdateAppBarColor(); UpdateInnerState(ViewerState.Single); } finally { HideProgress(); } }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (ExtraLarge != null) { hashCode = hashCode * 59 + ExtraLarge.GetHashCode(); } if (Large != null) { hashCode = hashCode * 59 + Large.GetHashCode(); } if (Standard != null) { hashCode = hashCode * 59 + Standard.GetHashCode(); } if (GridView != null) { hashCode = hashCode * 59 + GridView.GetHashCode(); } if (Small != null) { hashCode = hashCode * 59 + Small.GetHashCode(); } if (Thumbnail != null) { hashCode = hashCode * 59 + Thumbnail.GetHashCode(); } if (ExtraSmall != null) { hashCode = hashCode * 59 + ExtraSmall.GetHashCode(); } return(hashCode); } }
protected void Page_Load(object sender, EventArgs e) { string id = Request.QueryString["imgname"] as string; if (id == null) { Response.StatusCode = 404; Response.Write("Not Found"); Response.End(); return; } Thumbnail thumbnails = Session["file_info"] as Thumbnail; if (thumbnails == null) { Response.StatusCode = 404; Response.Write("Not Found"); Response.End(); return; } if (thumbnails.ID == id) { Response.ContentType = "image/jpeg"; Response.BinaryWrite(thumbnails.Data); Response.End(); return; } // If we reach here then we didn't find the file id so return 404 Response.StatusCode = 404; Response.Write("Not Found"); Response.End(); }
private void SaveAsImage_Click(object sender, RoutedEventArgs e) { List <string> list = null; //多批次图像 if (AggregativeType == AggregativeType.MultiBatch) { list = FilePathList; } //缩略图图像 else { list = Thumbnail.GetSelectedItemFileName(ItemNameType.AllItem); } if ((list == null) || (list.Count == 0)) { return; } System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); folderBrowserDialog.ShowDialog(); string selctPath = folderBrowserDialog.SelectedPath; for (int i = 0; i < list.Count; i++) { //string fileName = System.IO.Path.GetFileNameWithoutExtension(list[i]);//原来的 //fileName = System.IO.Path.GetFileName(list[i]);//原来的 //应its需求,在点击批量保存按钮时将文件名按照顺序号输出,wk,2018-8-23 string seq = (i + 1).ToString("000"); string fileExtension = System.IO.Path.GetExtension(list[i]); string fullName = selctPath + "\\" + seq + fileExtension; //string fullName = selctPath + "\\" + fileName;//原来的 File.Copy(list[i], fullName); } }
private void UpdateThumbnail(MessageViewModel message, Thumbnail thumbnail, Minithumbnail minithumbnail) { if (thumbnail != null) { var file = thumbnail.File; if (file.Local.IsDownloadingCompleted && thumbnail.Format is ThumbnailFormatJpeg) { Texture.Source = PlaceholderHelper.GetBlurred(file.Local.Path); } else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingActive) { if (minithumbnail != null) { Texture.Source = PlaceholderHelper.GetBlurred(minithumbnail.Data); } message.ProtoService.DownloadFile(file.Id, 1); } } else if (minithumbnail != null) { Texture.Source = PlaceholderHelper.GetBlurred(minithumbnail.Data); } }
protected override async Task LoadMorePropertiesCore(bool ForceUpdate) { RawData = await GetRawDataAsync(); if (!string.IsNullOrEmpty(RawData.LinkTargetPath)) { if (RawData.IconData.Length != 0) { using (MemoryStream IconStream = new MemoryStream(RawData.IconData)) { await Thumbnail.SetSourceAsync(IconStream.AsRandomAccessStream()); } } if (System.IO.Path.IsPathRooted(RawData.LinkTargetPath)) { LinkType = ShellLinkType.Normal; } else { LinkType = ShellLinkType.UWP; } } }
public static ImageDto ToImageDto(this Thumbnail thumbnail) { var tags = thumbnail.TagThumbnails.ToList().Select(t => t.Tag.ToTagDto()).ToList(); return(new ImageDto { Id = thumbnail.Id, FileSystemFolderId = thumbnail.FileSystemFolderId, FileName = thumbnail.FileName, Taken = thumbnail.FileCreateDateTime.ToShortDateString(), TakenTime = thumbnail.FileCreateDateTime.ToShortTimeString(), Tags = tags.Select(t => t.Id).ToList(), TagTypes = tags.Select(t => t.Type).Distinct().ToList(), PhotoBooks = thumbnail.PhotoBooks.Select(pb => pb.PhotoBookId).ToList(), Comments = thumbnail.Comments.Select(c => c.Id).ToList(), Faces = thumbnail.Faces.Where(f => !f.IsHidden).Select(f => f.Id).ToList(), Width = thumbnail.ImageWidth, Height = thumbnail.ImageHeight, Latitude = thumbnail.Latitude ?? thumbnail.Location?.Latitude, Longitude = thumbnail.Longitude ?? thumbnail.Location?.Longitude, LocationId = thumbnail.LocationId, Location = thumbnail.Location?.ToLocationDto() }); }
public Task <List <Thumbnail> > TestSplitAsync(string videoPath, int duration = 10, bool captureFirstScreen = true, bool captureLastScreen = true) { var thumbnails = new List <Thumbnail>(); try { // Get all files in the folder DirectoryInfo d = new DirectoryInfo(videoPath); FileInfo[] Files = d.GetFiles("*.png"); int i = 0; foreach (FileInfo file in Files) { TimeSpan time = TimeSpan.FromSeconds(i); string format = time.ToString(@"hh\:mm\:ss"); var source = file.FullName.Replace(@"\", @"\\"); var ocrPath = Path.Combine(Helper.GetBeforeLastIndexOf(source, '.') + ".txt"); var ocr = File.ReadAllText(ocrPath); var thumbnail = new Thumbnail() { Source = source, Time = format, OcrResult = ocr }; thumbnails.Add(thumbnail); i += 10; } } catch (Exception ex) { Console.WriteLine($"ImageExtractorService Exception: {ex.Message}"); } return(Task.FromResult(thumbnails)); }
public void Create_preview() { string actualExternalId = "someId"; MediaContentSource actualSource = MediaContentSource.YouTube; MediaContentType actualType = MediaContentType.Video; string actualTitle = "sometitle"; string actualDescription = "somedescription"; Thumbnail actualThumbnail = new Thumbnail(100, 100, "https://someurl.com"); var preview = new Preview( actualExternalId, actualSource, actualType, actualTitle, actualDescription, actualThumbnail); Assert.Equal(actualExternalId, preview.ContentId.ExternalId); Assert.Equal(actualSource, preview.ContentId.ContentSource); Assert.Equal(actualType, preview.ContentId.ContentType); Assert.Equal(actualTitle, preview.Title); Assert.Equal(actualDescription, preview.Description); Assert.Equal(actualThumbnail.Url, preview.Thumbnail.Url); }
public List <Thumbnail> GetThumbnails() { var photos = new List <Thumbnail>(); using (var con = new SqlConnection(conStr)) { SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT Id, Name, ThumbData, ContentType, Prise, Rating FROM dbo.Photos"; con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { var thumbnail = new Thumbnail(); thumbnail.Id = (int)reader["Id"]; thumbnail.Name = (string)reader["Name"]; thumbnail.ThumbData = (byte[])reader["ThumbData"]; thumbnail.ContentType = (string)reader["ContentType"]; thumbnail.Prise = (double)reader["Prise"]; thumbnail.Rating = (int)reader["Rating"]; photos.Add(thumbnail); } } return(photos); }
public override async Task PlaybackMovie(Thumbnail content) { if (MovieStreamHelper.INSTANCE.IsProcessing) { MovieStreamHelper.INSTANCE.Finish(); } MovieScreen.DataContext = MovieStreamHelper.INSTANCE.MoviePlaybackData; if (TargetDevice.Api.AvContent == null) { OnErrorMessage("Viewer_NoAvContentApi"); throw new IOException(); } var item = content.Source as ContentInfo; if (!item.RemotePlaybackAvailable) { OnErrorMessage("Viewer_UnplayableContent"); throw new IOException(); } var started = await MovieStreamHelper.INSTANCE.SetContentAndStart(TargetDevice.Api.AvContent, new PlaybackContent { Uri = (item as RemoteApiContentInfo).Uri, RemotePlayType = RemotePlayMode.SimpleStreaming, }, content.Source.Name); if (!started) { OnErrorMessage("Viewer_FailedPlaybackMovie"); throw new IOException(); } MovieScreen.NotifyStartingStreamingMoviePlayback(); }
public void UpdateIcons(Object threadContext) { if (TreeNodes.Count == 0) { return; } if (Cancel) { return; } ThreadRunning = true; Cancel = false; foreach (TreeNode item in TreeNodes) { if (Cancel) { break; } Invoke(new AddImageDelegate(AddImage), new object[] { Thumbnail.GetIcon(((PIDL)item.Tag).Pidl, 16), (PIDL)((PIDL)item.Tag).Clone(), item }); } Cancel = false; ThreadRunning = false; }
/// <summary> /// 裁剪图片并保存 /// </summary> public string CropSaveAs(string fileUri, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y) { string fileExt = Path.GetExtension(fileUri).Trim('.'); //文件扩展名,不含“.” if (string.IsNullOrEmpty(fileExt) || !IsImage(fileExt)) { return("{\"status\": 0, \"msg\": \"该文件不是图片!\"}"); } byte[] byteData = null; //判断是否远程文件 if (fileUri.ToLower().StartsWith("http://") || fileUri.ToLower().StartsWith("https://")) { WebClient client = new WebClient(); byteData = client.DownloadData(fileUri); client.Dispose(); } else //本地源文件 { string fullName = Utils.GetMapPath(fileUri); if (File.Exists(fullName)) { FileStream fs = File.OpenRead(fullName); BinaryReader br = new BinaryReader(fs); br.BaseStream.Seek(0, SeekOrigin.Begin); byteData = br.ReadBytes((int)br.BaseStream.Length); fs.Close(); } } //裁剪后得到文件流 byteData = Thumbnail.MakeThumbnailImage(byteData, fileExt, maxWidth, maxHeight, cropWidth, cropHeight, X, Y); //删除原图 DeleteFile(fileUri); //保存制作好的缩略图 return(FileSaveAs(byteData, fileUri, false, false)); }
public FileInfo LoadThumbnail(String hash, String mime) { FileInfo source = GetThumbnailFileInfo(hash); if (!source.Exists) { if (mime.StartsWith("image/")) { FileInfo originalImage = GetFileInfo(hash); Thumbnail.Create(new Uri(originalImage.FullName), mime, 256, source); // if the thumbnail was not created for some reason... if (!source.Exists) { source = null; } } else { source = null; } } return(source); }
private void addPortraitThumbnail( Person pers ) { var tn = pers.Thumbnails[pers.ThumbnailKey]; if ( tn==null ) tn = new Thumbnail(Global.Skola.HomePath,66,100,_tnsPortraits.Count.ToString()); _tnsPortraits.add( tn ); _hashPortrait.Add( tn, pers ); }
partial void OnThumbnailChanging(Thumbnail value);
/* * @author Ammar ALammar * @date 2014-07-05 * @description Wait for a response from the callout & wait for the whole attachment body * to be downloaded then assign as a texture to a game object * * @param www The wwwForm being executed. * * @modified by Ben Lyne on 8/1/2015 to include flipping and adding the thumbnail to the list. */ IEnumerator executeDownload(WWW www, int seq) { yield return www; if (www.error == null){ response = www.text; } else { response = www.error; } // Obtain the binary byte array of the textures textureBytes = www.bytes; // Assign textures to the images coming in from Salesforce. // Set small and then it will // automatically inherit the right size when it loads in the image immediately afterwards. Texture2D tex = new Texture2D(4, 4); tex.LoadImage(www.bytes); // Flip the image horizontally (for images taken with the BubblePix app) Texture2D flip = new Texture2D(tex.width,tex.height); int xN = tex.width; int yN = tex.height; // Loop through each pixel and reverse. for(int i = 1; i < xN; i++) { for(int j = 1; j < yN; j++) { flip.SetPixel(xN-i-1, j, tex.GetPixel(i,j)); } } // Execute the flip in the UI. flip.Apply(); // Add the thumbnail to the list of others. Thumbnail temp = new Thumbnail (flip, flip, Country (), Date ()); m_Thumbs.Add( temp ); //Debug.Log ("END DOWNLOAD"); }
protected override bool deleteThumbnail( Thumbnail tn, bool fQuery ) { if ( fQuery ) { if ( _person.ThumbnailKey == tn.Key ) { Global.showMsgBox( this, "Du får inte radera en vald bild!" ); return false; } return true; } if (SelectedThumbnailKey == _strThumbnailkeyRightClicked) { SelectedThumbnailKey = null; loadPhotoBox(null); } if ( _person.ThumbnailKey == tn.Key ) _person.ThumbnailKey = null; _person.Thumbnails.Delete( tn ); Invalidate(); updateLV( null ); return false; }
private async Task FetchItemGenreAndIonAsync(scan_pips_contributors item, Thumbnail thumbnail, IProgress progress, bool isTags, bool isIonContributors, bool isCategories) { if (progress.IsCancelled) { return; } thumbnail.ShowImage("http://node2.bbcimg.co.uk/iplayer/images/episode/" + item.pid + "_314_176.jpg"); try { if (isTags || isIonContributors) { WebClient client = new WebClient(); string result = await client.DownloadStringTaskAsync("http://www.bbc.co.uk/iplayer/ion/episodedetail/episode/" + item.pid + "/format/xml"); XElement episode = XElement.Parse(result); XNamespace ion = "http://bbc.co.uk/2008/iplayer/ion"; if (isIonContributors) { await TaskEx.Run(() => { var contributors = episode.Elements(ion + "blocklist") .Elements(ion + "episode_detail") .Elements(ion + "contributors") .Elements(ion + "contributor"); var data = new ReduxEntities(); foreach (var contributor in contributors) { var ct = new contributor { character_name = contributor.Element(ion + "character_name").Value, family_name = contributor.Element(ion + "family_name").Value, given_name = contributor.Element(ion + "given_name").Value, role = contributor.Element(ion + "role").Value, role_name = contributor.Element(ion + "role_name").Value, type = contributor.Element(ion + "type").Value, contributor_id = Convert.ToInt32(contributor.Element(ion + "id").Value), pid = item.pid }; data.AddObject("contributors", ct); } data.SaveChanges(); }); } if (isTags) { await TaskEx.Run(() => { var tags = episode.Elements(ion + "blocklist") .Elements(ion + "episode_detail") .Elements(ion + "tag_schemes") .Elements(ion + "tag_scheme") .Elements(ion + "tags") .Elements(ion + "tag"); var data = new ReduxEntities(); foreach (var tag in tags) { var tg = new tag { tag_id = tag.Element(ion + "id").Value, name = tag.Element(ion + "name").Value, value = tag.Element(ion + "value").Value, pid = item.pid }; data.AddObject("tags", tg); } data.SaveChanges(); }); } } if (isCategories) { WebClient catClient = new WebClient(); var catresult = await catClient.DownloadStringTaskAsync("http://www.bbc.co.uk/programmes/" + item.pid + ".xml"); var root = XElement.Parse(catresult); await TaskEx.Run(() => { var cats = from cat in root.XPathSelectElements("categories/category[@type != 'genre']") select new category() { pid = item.pid, type = cat.Attribute("type").Value, catkey = cat.Attribute("key").Value, title = cat.Element("title").Value }; var db = new ReduxEntities(); foreach (var c in cats) { db.AddObject("categories", c); } db.SaveChanges(); }); } item.scanned = true; } catch (WebException wex) { MessageBox.Show("Can't find programme " + item.pid); //throw new Exception("Couldn't find programme " + item.pid, wex); } }
public static ImageSize GetThumbnailImage(string dir, string filename, string outname, float width, float height, Thumbnail Thumbnailmode) { Image originalImage = Image.FromFile(dir + filename); return GetThumbnailImage(originalImage, outname, width, height, Thumbnailmode); }
public static ImageSize GetThumbnailImage(System.Web.HttpPostedFileBase postfile, string outname, float width, float height, Thumbnail Thumbnailmode) { return GetThumbnailImage(postfile.InputStream, outname, width, height, Thumbnailmode); }
/// <summary> /// 文件上传方法 /// </summary> /// <param name="postedFile">文件流</param> /// <param name="isThumbnail">是否生成缩略图</param> /// <param name="isWater">是否打水印</param> /// <returns>上传后文件信息</returns> public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater) { try { string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.” int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位 string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名 string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名 string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名 string upLoadPath = GetUpLoadPath(); //上传目录相对路径 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径 string newFilePath = upLoadPath + newFileName; //上传后的路径 string newThumbnailPath = upLoadPath + newThumbnailFileName; //上传后的缩略图路径 //检查文件扩展名是否合法 if (!CheckFileExt(fileExt)) { return("{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}"); } //检查文件大小是否合法 if (!CheckFileSize(fileExt, fileSize)) { return("{\"status\": 0, \"msg\": \"文件超过限制的大小啦!\"}"); } //检查上传的物理路径是否存在,不存在则创建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } //保存文件 postedFile.SaveAs(fullUpLoadPath + newFileName); //如果是图片,检查图片是否超出最大尺寸,是则裁剪 if (IsImage(fileExt) && (this.siteConfig.imgmaxheight > 0 || this.siteConfig.imgmaxwidth > 0)) { Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newFileName, this.siteConfig.imgmaxwidth, this.siteConfig.imgmaxheight); } //如果是图片,检查是否需要生成缩略图,是则生成 if (IsImage(fileExt) && isThumbnail && this.siteConfig.thumbnailwidth > 0 && this.siteConfig.thumbnailheight > 0) { Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName, this.siteConfig.thumbnailwidth, this.siteConfig.thumbnailheight, "Cut"); } //如果是图片,检查是否需要打水印 if (IsWaterMark(fileExt) && isWater) { switch (this.siteConfig.watermarktype) { case 1: WaterMark.AddImageSignText(newFilePath, newFilePath, this.siteConfig.watermarktext, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize); break; case 2: WaterMark.AddImageSignPic(newFilePath, newFilePath, this.siteConfig.watermarkpic, this.siteConfig.watermarkposition, this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency); break; } } //处理完毕,返回JOSN格式的文件信息 return("{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \"" + fileName + "\", \"path\": \"" + newFilePath + "\", \"thumb\": \"" + newThumbnailPath + "\", \"size\": " + fileSize + ", \"ext\": \"" + fileExt + "\"}"); } catch { return("{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}"); } }
private void zoom( Person person, Thumbnail tn ) { var tnSelected = frmZoom.showDialog( FindForm(), null, null, _flikKategori, person.Thumbnails, tn.Key, null, person.ThumbnailKey, null); if (tnSelected == null || tnSelected.Key == person.ThumbnailKey) return; if (Global.askMsgBox(this, "Vill du ändra den valda bilden?", true) != DialogResult.Yes) return; person.ThumbnailKey = tnSelected.Key; Invalidate(); }
public void pagingall(List <ProductSQL> acs, PaginationMetadataModel page) { var config = ConfigController.GetByTop1(); string cssClass = "col-xs-6"; StringBuilder html = new StringBuilder(); html.Append("<div class='row'>"); if (acs.Count > 0) { PageCount = page.totalPages; Int32 Page = page.currentPage; var index = 0; foreach (var item in acs) { html.Append("<div class='col-md-3 item-" + index + " product-item'>"); html.Append("<div class='row'>"); html.Append(" <div class='col-xs-12'>"); html.Append(" <p><a href='/xem-nuoc-hoa?id=" + item.ID + "'><img src='" + Thumbnail.getURL(item.ProductImage, Thumbnail.Size.Large) + "'></a></p>"); html.Append(" <h3 class='product-name'><a href='/xem-nuoc-hoa?id=" + item.ID + "'>" + item.ProductSKU + " - " + item.ProductTitle + "</a></h3>"); html.Append(" <h3><span class='product-price'>Giá sỉ: " + string.Format("{0:N0}", item.RegularPrice) + "</span> - <span class='product-price price-retail'>Giá lẻ: " + string.Format("{0:N0}", item.RetailPrice) + "</span></h3>"); if (!string.IsNullOrEmpty(item.Materials)) { html.Append(" <p>" + item.Materials + "</p>"); } html.Append(" </div>"); html.Append("</div>"); html.Append("<div class='row'>"); html.Append(" <div class='col-xs-12'>"); html.Append(" <div class='" + cssClass + "'>"); html.Append(" <div class='row'>"); html.Append(" <a href='javascript:;' class='btn primary-btn copy-btn h45-btn' onclick='copyProductInfo(" + item.ID + ");'><i class='fa fa-files-o' aria-hidden='true'></i> Copy mô tả</a>"); html.Append(" </div>"); html.Append(" </div>"); html.Append(" <div class='" + cssClass + "'>"); html.Append(" <div class='row'>"); html.Append(" <a href ='javascript:;' class='btn primary-btn h45-btn' onclick='getAllProductImage(`" + item.ProductSKU + "`);'><i class='fa fa-cloud-download' aria-hidden='true'></i> Tải hình</a>"); html.Append(" </div>"); html.Append(" </div>"); html.Append(" </div>"); html.Append("</div>"); html.Append("</div>"); if ((index + 1) % 4 == 0) { html.Append("<div class='clear'></div>"); } index++; } } else { html.Append("<div class='col-md-12'>Không tìm thấy sản phẩm...</div>"); } html.Append("</div>"); ltrList.Text = html.ToString(); }
protected override void tnRightClick( Thumbnail tn, Point p ) { _strThumbnailkeyRightClicked = tn.Key; int nFlyttaIndex = mnuThumbFlytta.Index; mnuThumb.MenuItems.RemoveAt( nFlyttaIndex ); mnuThumbFlytta.MenuItems.Clear(); foreach ( var grupp in Global.Skola.Grupper ) if ( grupp!=_grupp && grupp.GruppTyp==GruppTyp.GruppNormal ) mnuThumbFlytta.MenuItems.Add(new MenuItem(grupp.Namn, mnuThumbFlytta_Click)); mnuThumb.MenuItems.Add( nFlyttaIndex, mnuThumbFlytta ); base.tnRightClick( tn, p ); }
protected override void thumbnailClicked( Thumbnail tn, bool doubleClick ) { if (tn == null) return; if (ModifierKeys == Keys.Control && !doubleClick) { if (SelectedThumbnailKey == tn.Key) return; if (SelectedThumbnailKeys.Contains(tn.Key)) SelectedThumbnailKeys.Remove(tn.Key); else SelectedThumbnailKeys.Add(tn.Key); Invalidate(); return; } if (SelectedThumbnailKey != tn.Key) { SelectedThumbnailKey = tn.Key; loadPhotoBox(tn.loadViewImage()); var fn = tn.GetBackdroppedFilename(); if (fn != null) _backdroppedImage = new Bitmap(fn); } if (doubleClick) { if (_person.ThumbnailKey != SelectedThumbnailKey) { if (_person.ThumbnailLocked && ModifierKeys != Keys.Control) { Global.showMsgBox(this, "Eftersom bilden är låst måste du hålla in Ctrl-tangenten samtidigt som du dubbelklickar för att byta bild!"); return; } _person.ThumbnailKey = SelectedThumbnailKey; updateLV(null); } _person.ThumbnailLocked = true; } Invalidate(); }
protected void makeNewThumbnailVisible( Thumbnail tn ) { var tns = getThumbnails(); resize( ClientSize ); tns.ensureVisible( tn ); scrThumb.Maximum = Math.Max( scrThumb.Maximum, tns.FirstImage ); scrThumb.Value = tns.FirstImage; Invalidate(); }
protected override void tnRightClick(Thumbnail tn, Point p) { if (!SelectedThumbnailKeys.Contains(tn.Key)) thumbnailClicked(tn, false); var single = SelectedThumbnailKeys.Count == 1; mnuThumbRadera.Enabled = single; base.tnRightClick(tn, p); }
public static string getAllCategoryImage(double productPrice = 0) { List <string> result = new List <string>(); string rootPath = HostingEnvironment.ApplicationPhysicalPath; string uploadsImagesPath = rootPath + "/uploads/images/"; using (var dbe = new inventorymanagementEntities()) { var products = dbe.tbl_Product.Where(p => p.CategoryID == 44).OrderByDescending(o => o.ID).ToList(); if (productPrice > 0) { products = products.Where(p => p.Regular_Price == productPrice).ToList(); } else if (productPrice == -1) { products = products.Where(p => p.Regular_Price != 30000 && p.Regular_Price != 35000 && p.Regular_Price != 49000 && p.Regular_Price != 135000).ToList(); } if (products != null) { List <string> images = new List <string>(); foreach (var item in products) { var stock = StockManagerController.getStock(item.ID, 0); double quantity = 0; if (stock.Count > 0) { quantity = stock .Select(s => s.Type == 2 ? (s.QuantityCurrent.Value - s.Quantity.Value) : (s.QuantityCurrent.Value + s.Quantity.Value)) .Sum(s => s); } // Chỉ lấy ảnh sản phẩm còn hàng if (quantity >= 3) { // lấy ảnh đại diện string imgAdd = item.ProductImage; if (File.Exists(uploadsImagesPath + imgAdd)) { images.Add(imgAdd); } // lấy ảnh sản phẩm từ thư viện var imageProduct = ProductImageController.GetByProductID(item.ID); if (imageProduct != null) { foreach (var img in imageProduct) { imgAdd = img.ProductImage; if (File.Exists(uploadsImagesPath + imgAdd)) { images.Add(imgAdd); } } } // lấy ảnh sản phẩm từ biến thể var variable = ProductVariableController.GetByParentSKU(item.ProductSKU); if (variable != null) { foreach (var v in variable) { if (!String.IsNullOrEmpty(v.Image)) { imgAdd = v.Image; if (File.Exists(uploadsImagesPath + imgAdd)) { images.Add(imgAdd); } } } } } } images = images.Distinct().ToList(); if (images.Count() > 0) { // lấy hình gốc for (int i = 0; i < images.Count; i++) { result.Add(Thumbnail.getURL(images[i], Thumbnail.Size.Source)); } } } } JavaScriptSerializer serializer = new JavaScriptSerializer(); return(serializer.Serialize(result.ToList())); }
protected virtual void thumbnailClicked( Thumbnail tn, bool fDoubleClick ) { }
private ProjectFile ProcessProjectFile(TempUploadedFile file, Thumbnail thumb) { if (file == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : file is null!", null); return(null); } Stream ms = new MemoryStream(); Metadata metadata = null; if (this.serviceLocalStorage.DownloadFile(ref ms, file.Path, _container)) { metadata = serviceWaveform.GetMetadata(file.Path, ms); } string internalName = this.GenerateProjectFileInternalName(file); string path = this.GenerateProjectFilePath(file); MogFile uploadedFile = null; if (file.StorageCredential == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : StorageCredential is null!", null); return(null); } switch (file.StorageCredential.CloudService) { case CloudStorageServices.Dropbox: uploadedFile = this.serviceDropbox.UploadFile((MemoryStream)ms, internalName, file.StorageCredential, path); if (uploadedFile == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : dropbox uploadedFile is null!", null); return(null); } uploadedFile.PublicUrl = this.serviceDropbox.GetMedialUrl(uploadedFile.Path, file.StorageCredential); break; case CloudStorageServices.Skydrive: uploadedFile = this.serviceSkydrive.UploadFile((MemoryStream)ms, internalName, file.StorageCredential, path); if (uploadedFile == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : Skydrive uploadedFile is null!", null); return(null); } uploadedFile.PublicUrl = this.serviceSkydrive.GetMedialUrl(uploadedFile.Path, file.StorageCredential); break; } ProjectFile projectFile = this.serviceMogFile.GetByTempFileId(file.Id); if (projectFile == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : projectFile is null!", null); return(null); } if (thumb != null) { projectFile.ThumbnailId = thumb.Id; } projectFile.Path = uploadedFile.Path; projectFile.PublicUrl = uploadedFile.PublicUrl; projectFile.TempFileId = null; projectFile.SetMetadata(metadata); this.serviceMogFile.SaveChanges(projectFile); return(projectFile); }
public override Task DeleteSelectedFile(Thumbnail item) { ContentsCollection.Remove(item); return(Task.Delay(100)); }
private static string SaveThumbnailImage(this HttpPostedFileBase file, string filename, string ext, int width, int height, Thumbnail ThumbnailMode) { string tfilename = string.Format("{0}_{1}x{2}", filename, width, height); ThumbnailImage.GetThumbnailImage(file, string.Format("{0}{1}", tfilename, ext), width, height, ThumbnailMode); return filename; }
public List <ProductCardModel> getProducts(ProductFilterModel filter, ref PaginationMetadataModel pagination) { using (var con = new SQLServerContext()) { var source = con.tbl_Product .Select(x => new { categoryID = x.CategoryID.HasValue ? x.CategoryID.Value : 0, productID = x.ID, sku = x.ProductSKU, title = x.ProductTitle, unSignedTitle = x.UnSignedTitle, slug = x.Slug, materials = x.Materials, preOrder = x.PreOrder, availability = false, avatar = x.ProductImage, regularPrice = x.Regular_Price.HasValue ? x.Regular_Price.Value : 0, oldPrice = x.Old_Price.HasValue ? x.Old_Price.Value : 0, retailPrice = x.Retail_Price.HasValue ? x.Retail_Price.Value : 0, content = x.ProductContent, webPublish = x.WebPublish.HasValue ? x.WebPublish.Value : false, webUpdate = x.WebUpdate, }); #region Lọc sản phẩm #region Lọc sản phẩm theo text search if (!String.IsNullOrEmpty(filter.productSearch)) { source = source .Where(x => ( ( x.sku.Trim().Length >= filter.productSearch.Trim().Length&& x.sku.Trim().ToLower().StartsWith(filter.productSearch.Trim().ToLower()) ) || ( x.sku.Trim().Length < filter.productSearch.Trim().Length&& filter.productSearch.Trim().ToLower().StartsWith(x.sku.Trim().ToLower()) ) ) || x.title.Trim().ToLower().Contains(filter.productSearch.Trim().ToLower()) || x.unSignedTitle.Trim().ToLower().Contains(filter.productSearch.Trim().ToLower()) ); } else { // Trường hợp không phải là search thì kiểm tra điều web public source = source.Where(x => x.webPublish == true); } #endregion #region Lọc sản phẩm theo tag slug if (!String.IsNullOrEmpty(filter.tagSlug)) { var tags = con.Tag.Where(x => x.Slug == filter.tagSlug.Trim().ToLower()); var prodTags = con.ProductTag .Join( tags, pt => pt.TagID, t => t.ID, (pt, t) => pt ); source = source .Join( prodTags, p => p.productID, t => t.ProductID, (p, t) => p ); } #endregion #region Lấy theo preOrder (hang-co-san | hang-order) if (!String.IsNullOrEmpty(filter.productBadge)) { switch (filter.productBadge) { case "hang-co-san": source = source.Where(x => x.preOrder == false); break; case "hang-order": source = source.Where(x => x.preOrder == true); break; case "hang-sale": source = source.Where(x => x.oldPrice > 0); break; default: break; } } #endregion #region Lấy theo wholesale price if (filter.priceMin > 0) { source = source.Where(x => x.regularPrice >= filter.priceMin); } if (filter.priceMax > 0) { source = source.Where(x => x.regularPrice <= filter.priceMax); } #endregion #region Lấy theo category slug if (!String.IsNullOrEmpty(filter.categorySlug)) { var categories = _category.getCategoryChild(filter.categorySlug); if (categories == null || categories.Count == 0) { return(null); } var categoryIDs = categories.Select(x => x.id).OrderByDescending(o => o).ToList(); source = source.Where(x => categoryIDs.Contains(x.categoryID)); } #endregion #region Lấy theo category slug if (filter.categorySlugList != null && filter.categorySlugList.Count > 0) { var categories = new List <ProductCategoryModel>(); foreach (var categorySlug in filter.categorySlugList) { var categoryChilds = _category.getCategoryChild(categorySlug); if (categoryChilds == null || categoryChilds.Count == 0) { continue; } categories.AddRange(categoryChilds); } if (categories == null || categories.Count == 0) { return(null); } var categoryIDs = categories.Select(x => x.id).Distinct().OrderByDescending(o => o).ToList(); source = source.Where(x => categoryIDs.Contains(x.categoryID)); } #endregion #region Lấy thông tin sản phẩm và stock var stockFilter = con.tbl_StockManager .Join( source, s => s.ParentID, d => d.productID, (s, d) => s ) .ToList(); var stocks = _stock.getQuantities(stockFilter); #endregion #region Lấy sản phẩm đạt yêu cầu var data = source .ToList() .GroupJoin( stocks, pro => pro.productID, info => info.productID, (pro, info) => new { pro, info } ) .SelectMany( x => x.info.DefaultIfEmpty(), (parent, child) => new { product = parent.pro, stock = child } ) .Select(x => new { x.product, x.stock }); // Trường hợp không phải là search thì kiểm tra điều kiện stock if (String.IsNullOrEmpty(filter.productSearch)) { data = data.Where(x => x.product.preOrder || x.stock == null || ( x.stock != null && x.stock.quantity >= (x.product.categoryID == 44 ? 1 : 3) ) ); } #endregion #endregion #region Thực hiện sắp xếp sản phẩm if (filter.productSort == (int)ProductSortKind.PriceAsc) { data = data.OrderBy(o => o.product.regularPrice); } else if (filter.productSort == (int)ProductSortKind.PriceDesc) { data = data.OrderByDescending(o => o.product.regularPrice); } else if (filter.productSort == (int)ProductSortKind.ModelNew) { data = data.OrderByDescending(o => o.product.productID); } else if (filter.productSort == (int)ProductSortKind.ProductNew) { data = data.OrderByDescending(o => o.product.webUpdate); } else { data = data.OrderByDescending(o => o.product.webUpdate); } #endregion #region Thực hiện phân trang // Lấy tổng số record sản phẩm pagination.totalCount = data.Count(); // Calculating Totalpage by Dividing (No of Records / Pagesize) pagination.totalPages = (int)Math.Ceiling(pagination.totalCount / (double)pagination.pageSize); // Returns List of product after applying Paging var result = data .Select(x => new ProductCardModel() { productID = x.product.productID, sku = x.product.sku, name = x.product.title, slug = x.product.slug, materials = x.product.materials, badge = x.stock == null ? ProductBadge.warehousing : (x.product.oldPrice > 0 ? ProductBadge.sale : (x.product.preOrder ? ProductBadge.order : (x.stock.availability ? ProductBadge.stockIn : ProductBadge.stockOut))), availability = x.stock != null ? x.stock.availability : x.product.availability, thumbnails = Thumbnail.getALL(x.product.avatar), regularPrice = x.product.regularPrice, oldPrice = x.product.oldPrice, retailPrice = x.product.retailPrice, content = x.product.content }) .Skip((pagination.currentPage - 1) * pagination.pageSize) .Take(pagination.pageSize) .ToList(); // if CurrentPage is greater than 1 means it has previousPage pagination.previousPage = pagination.currentPage > 1 ? "Yes" : "No"; // if TotalPages is greater than CurrentPage means it has nextPage pagination.nextPage = pagination.currentPage < pagination.totalPages ? "Yes" : "No"; #endregion #region Lấy thông tin variable var colors = getColors(result.Select(x => x.productID).ToList()); var sizes = getSizes(result.Select(x => x.productID).ToList()); foreach (var prod in result) { prod.colors = colors.Where(x => x.productID == prod.productID).ToList(); prod.sizes = sizes.Where(x => x.productID == prod.productID).ToList(); } #endregion return(result); } }
public override Task PlaybackMovie(Thumbnail item) { throw new NotImplementedException(); }
/// <summary> /// Updates thumbnails in XMP data of Jpeg file and creates output file /// </summary> public static void UpdateThumbnailInXMPData() { try { //ExStart:UpdateThumbnailXmpPropertiesJpegImage string path = Common.MapSourceFilePath(filePath); // initialize JpegFormat JpegFormat jpegFormat = new JpegFormat(Common.MapSourceFilePath(filePath)); // get image base64 string string base64String; using (Image image = Image.FromFile(path)) { using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); // Convert byte[] to Base64 String base64String = Convert.ToBase64String(imageBytes); } } // create image thumbnail Thumbnail thumbnail = new Thumbnail { ImageBase64 = base64String }; // initialize array and add thumbnail Thumbnail[] thumbnails = new Thumbnail[1]; thumbnails[0] = thumbnail; // update thumbnails property in XMP Basic schema jpegFormat.XmpValues.Schemes.XmpBasic.Thumbnails = thumbnails; // commit changes jpegFormat.Save(Common.MapDestinationFilePath(filePath)); //ExEnd:UpdateThumbnailXmpPropertiesJpegImage Console.WriteLine("File saved in destination folder."); } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> /// Lấy thông tin sản phẩm theo slug /// </summary> /// <param name="slug"></param> /// <returns></returns> public ProductModel getProductBySlug(string slug) { using (var con = new SQLServerContext()) { // Kiểm tra có sản phẩm không var data = con.tbl_Product.Where(x => x.Slug == slug); if (data.FirstOrDefault() == null) { return(null); } // Lấy ID sản phẩm var id = data.FirstOrDefault().ID; // Get quantity var stockFilter = con.tbl_StockManager .Join( data, s => s.ParentID, d => d.ID, (s, d) => s ) //.OrderBy(x => new { x.ParentID.Value, x.ProductID, x.ProductVariableID }) .ToList(); var stocks = _stock.getQuantities(stockFilter); // Get info variable var colors = getColors(id); var sizes = getSizes(id); // Get images of product var images = getImageListByProduct(id); // Get tags of product var tags = getTagListByProduct(id); // Xuất thông tin cơ bản của sản phẩm var products = data.Where(x => x.CategoryID.HasValue) .Join( con.tbl_Category, pro => pro.CategoryID.Value, cat => cat.ID, (p, c) => new { id = p.ID, categoryName = c.CategoryName, categorySlug = c.Slug, name = p.ProductTitle, sku = p.ProductSKU, avatar = !String.IsNullOrEmpty(p.ProductImageClean) ? p.ProductImageClean : p.ProductImage, materials = p.Materials, regularPrice = p.Regular_Price.HasValue ? p.Regular_Price.Value : 0, oldPrice = p.Old_Price.HasValue ? p.Old_Price.Value : 0, retailPrice = p.Retail_Price.HasValue ? p.Retail_Price.Value : 0, content = p.ProductContent, slug = p.Slug, preOrder = p.PreOrder, productStyle = p.ProductStyle.HasValue ? p.ProductStyle.Value : 1, shortDescription = p.ShortDescription, Price10 = p.Price10.HasValue ? p.Price10.Value : 0, BestPrice = p.BestPrice.HasValue ? p.BestPrice.Value : 0, CleanName = p.CleanName, FeaturedImage = p.FeaturedImage } ) .OrderBy(x => x.id) .ToList(); // Lấy tất cả thông tin về sản phẩm var result = products .GroupJoin( stocks, pro => pro.id, info => info.productID, (pro, info) => new { pro, info } ) .SelectMany( x => x.info.DefaultIfEmpty(), (parent, child) => new ProductModel() { id = parent.pro.id, categorySlug = parent.pro.categorySlug, categoryName = parent.pro.categoryName, name = parent.pro.name, sku = parent.pro.sku, avatar = parent.pro.avatar, thumbnails = Thumbnail.getALL(parent.pro.avatar), materials = parent.pro.materials, regularPrice = parent.pro.regularPrice, oldPrice = parent.pro.oldPrice, retailPrice = parent.pro.retailPrice, content = parent.pro.content, slug = parent.pro.slug, images = images, colors = colors, sizes = sizes, badge = child == null ? ProductBadge.warehousing : (parent.pro.oldPrice > 0 ? ProductBadge.sale : (parent.pro.preOrder ? ProductBadge.order : (child.availability ? ProductBadge.stockIn : ProductBadge.stockOut))), tags = tags, type = parent.pro.productStyle == 1 ? "simple" : "variable", manage_stock = parent.pro.productStyle == 1 ? true : false, stock_quantity = parent.pro.productStyle == 1 ? (child != null ? child.quantity : 0) : 0, short_description = parent.pro.shortDescription, Price10 = parent.pro.Price10, BestPrice = parent.pro.BestPrice, CleanName = parent.pro.CleanName, FeaturedImage = parent.pro.FeaturedImage } ) .OrderBy(o => o.id) .ToList(); return(result.FirstOrDefault()); } }
// Use this for initialization IEnumerator Start() { SVManager = StreetViewManager.Instance; thumbnail = Thumbnail.Instance(); GestureController.OnCursorOver += GestureController_OnCursorOver; GestureController.OnCursorOut += GestureController_OnCursorOut; GestureController.OnClicked += GestureController_OnClicked; yield return StartCoroutine(GetThumbnailImage(thumbnailURL)); while (!retrieveMetaData) { yield return StartCoroutine(GetLocationText(metaURL + panoID)); } //StartCoroutine(GetWikiKeyword(wikiSearchURL + searchKeyword)); //StartCoroutine(GetWikiData(wikiURL + searchKeyword)); }
private void WriteIFD(MemoryStream stream, Dictionary <ExifTag, ExifProperty> ifd, IFD ifdtype, long tiffoffset, bool preserveMakerNote) { BitConverterEx conv = new BitConverterEx(BitConverterEx.ByteOrder.System, ByteOrder); // Create a queue of fields to write Queue <ExifProperty> fieldqueue = new Queue <ExifProperty>(); foreach (ExifProperty prop in ifd.Values) { if (prop.Tag != ExifTag.MakerNote) { fieldqueue.Enqueue(prop); } } // Push the maker note data to the end if (ifd.ContainsKey(ExifTag.MakerNote)) { fieldqueue.Enqueue(ifd[ExifTag.MakerNote]); } // Offset to start of field data from start of TIFF header uint dataoffset = (uint)(2 + ifd.Count * 12 + 4 + stream.Position - tiffoffset); uint currentdataoffset = dataoffset; long absolutedataoffset = stream.Position + (2 + ifd.Count * 12 + 4); bool makernotewritten = false; // Field count stream.Write(conv.GetBytes((ushort)ifd.Count), 0, 2); // Fields while (fieldqueue.Count != 0) { ExifProperty field = fieldqueue.Dequeue(); ExifInterOperability interop = field.Interoperability; uint fillerbytecount = 0; // Try to preserve the makernote data offset if (!makernotewritten && !makerNoteProcessed && makerNoteOffset != 0 && ifdtype == IFD.EXIF && field.Tag != ExifTag.MakerNote && interop.Data.Length > 4 && currentdataoffset + interop.Data.Length > makerNoteOffset && ifd.ContainsKey(ExifTag.MakerNote)) { // Delay writing this field until we write makernote data fieldqueue.Enqueue(field); continue; } else if (field.Tag == ExifTag.MakerNote) { makernotewritten = true; // We may need to write filler bytes to preserve maker note offset if (preserveMakerNote && !makerNoteProcessed) { fillerbytecount = makerNoteOffset - currentdataoffset; } else { fillerbytecount = 0; } } // Tag stream.Write(conv.GetBytes(interop.TagID), 0, 2); // Type stream.Write(conv.GetBytes(interop.TypeID), 0, 2); // Count stream.Write(conv.GetBytes(interop.Count), 0, 4); // Field data byte[] data = interop.Data; if (ByteOrder != BitConverterEx.SystemByteOrder) { if (interop.TypeID == 1 || interop.TypeID == 3 || interop.TypeID == 4 || interop.TypeID == 9) { Array.Reverse(data); } else if (interop.TypeID == 5 || interop.TypeID == 10) { Array.Reverse(data, 0, 4); Array.Reverse(data, 4, 4); } } // Fields containing offsets to other IFDs // Just store their offets, we will write the values later on when we know the lengths of IFDs if (ifdtype == IFD.Zeroth && interop.TagID == 0x8769) { exifIFDFieldOffset = stream.Position; } else if (ifdtype == IFD.Zeroth && interop.TagID == 0x8825) { gpsIFDFieldOffset = stream.Position; } else if (ifdtype == IFD.EXIF && interop.TagID == 0xa005) { interopIFDFieldOffset = stream.Position; } else if (ifdtype == IFD.First && interop.TagID == 0x201) { thumbOffsetLocation = stream.Position; } else if (ifdtype == IFD.First && interop.TagID == 0x202) { thumbSizeLocation = stream.Position; } // Write 4 byte field value or field data if (data.Length <= 4) { stream.Write(data, 0, data.Length); for (int i = data.Length; i < 4; i++) { stream.WriteByte(0); } } else { // Pointer to data area relative to TIFF header stream.Write(conv.GetBytes(currentdataoffset + fillerbytecount), 0, 4); // Actual data long currentoffset = stream.Position; stream.Seek(absolutedataoffset, SeekOrigin.Begin); // Write filler bytes for (int i = 0; i < fillerbytecount; i++) { stream.WriteByte(0xFF); } stream.Write(data, 0, data.Length); stream.Seek(currentoffset, SeekOrigin.Begin); // Increment pointers currentdataoffset += fillerbytecount + (uint)data.Length; absolutedataoffset += fillerbytecount + data.Length; } } // Offset to 1st IFD // We will write zeros for now. This will be filled after we write all IFDs if (ifdtype == IFD.Zeroth) { firstIFDFieldOffset = stream.Position; } stream.Write(new byte[] { 0, 0, 0, 0 }, 0, 4); // Seek to end of IFD stream.Seek(absolutedataoffset, SeekOrigin.Begin); // Write thumbnail data if (ifdtype == IFD.First) { if (Thumbnail != null) { MemoryStream ts = new MemoryStream(); Thumbnail.Save(ts); ts.Close(); byte[] thumb = ts.ToArray(); thumbOffsetValue = (uint)(stream.Position - tiffoffset); thumbSizeValue = (uint)thumb.Length; stream.Write(thumb, 0, thumb.Length); ts.Dispose(); } else { thumbOffsetValue = 0; thumbSizeValue = 0; } } }
private ProjectFile ProcessProjectFile(TempUploadedFile file, Thumbnail thumb) { if (file == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : file is null!",null); return null; } Stream ms = new MemoryStream(); Metadata metadata = null; if (this.serviceLocalStorage.DownloadFile(ref ms, file.Path, _container)) { metadata = serviceWaveform.GetMetadata(file.Path, ms); } string internalName = this.GenerateProjectFileInternalName(file); string path = this.GenerateProjectFilePath(file); MogFile uploadedFile = null; if (file.StorageCredential == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : StorageCredential is null!", null); return null; } switch (file.StorageCredential.CloudService) { case CloudStorageServices.Dropbox: uploadedFile = this.serviceDropbox.UploadFile((MemoryStream)ms, internalName, file.StorageCredential, path); if (uploadedFile == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : dropbox uploadedFile is null!", null); return null; } uploadedFile.PublicUrl = this.serviceDropbox.GetMedialUrl(uploadedFile.Path, file.StorageCredential); break; case CloudStorageServices.Skydrive : uploadedFile = this.serviceSkydrive.UploadFile((MemoryStream)ms, internalName, file.StorageCredential, path); if (uploadedFile == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : Skydrive uploadedFile is null!", null); return null; } uploadedFile.PublicUrl = this.serviceSkydrive.GetMedialUrl(uploadedFile.Path, file.StorageCredential); break; } ProjectFile projectFile = this.serviceMogFile.GetByTempFileId(file.Id); if (projectFile == null) { this.serviceLog.LogError("TempFileService::ProcessProjectFile", "WTF : projectFile is null!", null); return null; } if (thumb != null) { projectFile.ThumbnailId = thumb.Id; } projectFile.Path = uploadedFile.Path; projectFile.PublicUrl = uploadedFile.PublicUrl; projectFile.TempFileId = null; projectFile.SetMetadata(metadata); this.serviceMogFile.SaveChanges(projectFile); return projectFile; }
public static ImageSize GetThumbnailImage(Stream str, string outname, float width, float height, Thumbnail Thumbnailmode) { Image originalImage = Image.FromStream(str); return GetThumbnailImage(originalImage, outname, width, height, Thumbnailmode); }
private Thumbnail ProcessThumbnail(TempUploadedFile file) { Thumbnail thumb = null; try { Stream ms = new MemoryStream(); string thumbPublicUrl = string.Empty; if (this.serviceLocalStorage.DownloadFile(ref ms, file.Path, _container)) { var picture = serviceWaveform.GetWaveform(file.Path, ms); byte[] pictureasByteArray = BitmapHelper.ImageToByte2(picture); thumbPublicUrl = this.serviceLocalStorage.UploadFile(pictureasByteArray, file.Path, "projects"); } ms.Close(); string internalName = GenerateThumbnailName(file); string path = GenerateThumbnailPath(file); thumb = new Thumbnail() { AuthCredentialId = file.AuthCredentialId, DisplayName = file.Name, InternalName = internalName, Path = path, PublicUrl = thumbPublicUrl//dropboxsavedFile.PublicUrl }; } catch (Exception exc) { this.serviceLog.LogError("TempFileService::Process-Thumbnail", exc); thumb = new Thumbnail() { PublicUrl = "/content/images/thumbnail_error.png" }; } this.repositoryThumbnail.Create(thumb); return thumb; }
public static ImageSize GetThumbnailImage(Image originalImage, string outname, float width, float height, Thumbnail Thumbnailmode) { float x = 0; float y = 0; float w = originalImage.Width; float h = originalImage.Height; #region A //if (originalImage.Width > width && originalImage.Height > height) //{ // if (originalImage.Width > originalImage.Height) // { // w = width; // h = width * originalImage.Height / originalImage.Width; // x = 0; // y = (height - h) / 2; // if (h > height) // { // h = height; // w = height * originalImage.Width / originalImage.Height; // x = (width - w) / 2; // y = 0; // } // } // else // { // h = height; // w = height * (float)originalImage.Width / (float)originalImage.Height; // x = (width - w) / 2; // y = 0; // if (w > width) // { // w = width; // h = width * (float)originalImage.Height / (float)originalImage.Width; // x = 0; // y = (height - h) / 2; // } // } //} //else if ((float)originalImage.Width > width) //{ // w = width; // h = width * (float)originalImage.Height / (float)originalImage.Width; // x = 0; // y = (height - h) / 2; //} //else if ((float)originalImage.Height > height) //{ // h = height; // w = height * (float)originalImage.Width / (float)originalImage.Height; // x = (width - w) / 2; // y = 0; //} //else //{ // w = (float)originalImage.Width; // h = (float)originalImage.Height; // x = (width - w) / 2; // y = (height - h) / 2; //} //if (auto) //{ // x = 0; // y = 0; //} #endregion switch (Thumbnailmode) { case Thumbnail.HW: break; case Thumbnail.W: height = originalImage.Height * width / originalImage.Width; break; case Thumbnail.H: width = originalImage.Width * height / originalImage.Height; break; case Thumbnail.Cut: if ((double)originalImage.Width / (double)originalImage.Height > (double)width / (double)width) { h = originalImage.Height; w = originalImage.Height * width / height; y = 0; x = (originalImage.Width - w) / 2; } else { w = originalImage.Width; h = originalImage.Width * height / width; x = 0; y = (originalImage.Height - h) * 0.382f; } break; case Thumbnail.AutoWH: if ((double)originalImage.Width / (double)originalImage.Height < (double)width / (double)width) { h = originalImage.Height; w = originalImage.Height * width / height; y = (originalImage.Height - h) / 2; x = (originalImage.Width - w) / 2; } else { w = originalImage.Width; h = originalImage.Width * height / width; x = (originalImage.Width - w) / 2; y = (originalImage.Height - h) / 2; } break; case Thumbnail.Auto: if (originalImage.Width < width && originalImage.Height < height) { width = originalImage.Width; height = originalImage.Height; } else if (originalImage.Width < width && originalImage.Height > height) { height = originalImage.Height * width / originalImage.Width; } else if (originalImage.Height < height && originalImage.Width > width) { width = originalImage.Width * height / originalImage.Height; } else { if (originalImage.Width > originalImage.Height) { height = originalImage.Height * width / originalImage.Width; } else { width = originalImage.Width * height / originalImage.Height; } } break; default: break; } Bitmap bm = new Bitmap((int)width, (int)height); Graphics g = Graphics.FromImage(bm); g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.Clear(Color.White); //g.DrawImage(originalImage, new Rectangle((int)x, (int)y, (int)w, (int)h), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel); g.DrawImage(originalImage, new Rectangle(0, 0, (int)width, (int)height), new Rectangle((int)x, (int)y, (int)w, (int)h), GraphicsUnit.Pixel); long[] quality = new long[1]; quality[0] = 100; System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICI = null; string fd = outname.Substring(outname.LastIndexOf('.')).ToLower().TrimStart('.'); fd = fd == "jpg" ? "JPEG" : fd == "gif" ? "GIF" : fd.ToUpper(); for (int i = 0; i < arrayICI.Length; i++) { if (arrayICI[i].FormatDescription.Equals(fd)) { jpegICI = arrayICI[i]; break; } } if (jpegICI != null) { System.IO.File.Delete(outname); bm.Save(outname, jpegICI, encoderParams); } bm.Dispose(); originalImage.Dispose(); g.Dispose(); return new ImageSize() { width = width, height = height }; }
protected void Page_Load(object sender, EventArgs e) { System.Drawing.Image thumbnail_image = null; System.Drawing.Image original_image = null; System.Drawing.Bitmap final_image = null; System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { // Get the data HttpPostedFile jpeg_image_upload = Request.Files["Filedata"]; // Retrieve the uploaded image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); // Calculate the new width and height int width = original_image.Width; int height = original_image.Height; int target_width = 100; int target_height = 100; int new_width, new_height; float target_ratio = (float)target_width / (float)target_height; float image_ratio = (float)width / (float)height; if (target_ratio > image_ratio) { new_height = target_height; new_width = (int)Math.Floor(image_ratio * (float)target_height); } else { new_height = (int)Math.Floor((float)target_width / image_ratio); new_width = target_width; } new_width = new_width > target_width ? target_width : new_width; new_height = new_height > target_height ? target_height : new_height; // Create the thumbnail // Old way //thumbnail_image = original_image.GetThumbnailImage(new_width, new_height, null, System.IntPtr.Zero); // We don't have to create a Thumbnail since the DrawImage method will resize, but the GetThumbnailImage looks better // I've read about a problem with GetThumbnailImage. If a jpeg has an embedded thumbnail it will use and resize it which // can result in a tiny 40x40 thumbnail being stretch up to our target size final_image = new System.Drawing.Bitmap(target_width, target_height); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height)); int paste_x = (target_width - new_width) / 2; int paste_y = (target_height - new_height) / 2; graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */ //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height); graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height); // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo) ms = new MemoryStream(); final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // Store the data in my custom Thumbnail object string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer()); // Put it all in the Session (initialize the session if necessary) List<Thumbnail> thumbnails = Session["file_info"] as List<Thumbnail>; if (thumbnails == null) { thumbnails = new List<Thumbnail>(); Session["file_info"] = thumbnails; } thumbnails.Add(thumb); Response.StatusCode = 200; Response.Write(thumbnail_id); } catch { // If any kind of error occurs return a 500 Internal Server error Response.StatusCode = 500; Response.Write("An error occured"); Response.End(); } finally { // Clean up if (final_image != null) final_image.Dispose(); if (graphic != null) graphic.Dispose(); if (original_image != null) original_image.Dispose(); if (thumbnail_image!= null )thumbnail_image.Dispose(); if (ms != null) ms.Close(); Response.End(); } }