public Picture(ByteVector data)
 {
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (data.Count < 0x20)
     {
         throw new CorruptFileException("Data must be at least 32 bytes long");
     }
     int startIndex = 0;
     this.type = (PictureType) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     int count = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     this.mime_type = data.ToString(StringType.Latin1, startIndex, count);
     startIndex += count;
     int num3 = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     this.description = data.ToString(StringType.UTF8, startIndex, num3);
     startIndex += num3;
     this.width = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     this.height = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     this.color_depth = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     this.indexed_colors = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     int length = (int) data.Mid(startIndex, 4).ToUInt();
     startIndex += 4;
     this.picture_data = data.Mid(startIndex, length);
 }
Beispiel #2
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Client.IEmployeeService"/>
        /// </summary>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <returns></returns>
        public async Task<Employee> GetLoggedEmployeeInfo(PictureType pictureType)
        {
            string url = String.Format(CultureInfo.InvariantCulture
              , "{0}api/employees/current/{1}", _urlPrefix, (int)pictureType);

            return await base.GetAsync<Employee>(url);
        }
 public static AttachedPictureFrame Get(TagLib.Id3v2.Tag tag, string description, PictureType type, bool create)
 {
     AttachedPictureFrame frame;
     IEnumerator<Frame> enumerator = tag.GetFrames(FrameType.APIC).GetEnumerator();
     try
     {
         while (enumerator.MoveNext())
         {
             Frame current = enumerator.Current;
             frame = current as AttachedPictureFrame;
             if (((frame != null) && ((description == null) || (frame.Description == description))) && ((type == PictureType.Other) || (frame.Type == type)))
             {
                 return frame;
             }
         }
     }
     finally
     {
         if (enumerator == null)
         {
         }
         enumerator.Dispose();
     }
     if (!create)
     {
         return null;
     }
     frame = new AttachedPictureFrame {
         Description = description,
         Type = type
     };
     tag.AddFrame(frame);
     return frame;
 }
Beispiel #4
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Client.IEmployeeService"/>
        /// </summary>
        /// <param name="filter"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <param name="pageSize"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <param name="pageCount"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <returns></returns>
        public async Task<IList<Employee>> GetEmployees(string filter, PictureType pictureType, int pageSize, int pageCount)
        {
            string url = String.Format(CultureInfo.InvariantCulture
              , "{0}api/employees/GetEmployees?filter={1}&pictureType={2}&pageSize={3}&pageCount={4}", _urlPrefix, filter, (int)pictureType, pageSize, pageCount);

            return await base.GetAsync<IList<Employee>>(url);
        }
Beispiel #5
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Client.IEmployeeService"/>
        /// </summary>
        /// <param name="employeeId"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Client.IEmployeeService"/></param>
        /// <returns></returns>
        public async Task<Employee> Get(int employeeId, PictureType pictureType)
        {
            string url = String.Format(CultureInfo.InvariantCulture
              , "{0}api/employees/{1}/{2}", _urlPrefix, employeeId, (int)pictureType);

            return await base.GetAsync<Employee>(url);
        }
Beispiel #6
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Client.IVisitService"/>
        /// </summary>
        /// <param name="visitId"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <returns><see cref="MyCompany.Visitors.Client.IVisitService"/></returns>
        public async Task<Visit> Get(int visitId, PictureType pictureType)
        {
            string url = String.Format(CultureInfo.InvariantCulture
              , "{0}api/visits/{1}/{2}", _urlPrefix, visitId, (int)pictureType);

            return await base.GetAsync<Visit>(url);
        }
Beispiel #7
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Client.IVisitService"/>
        /// </summary>
        /// <param name="filter"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <param name="pageSize"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <param name="pageCount"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <param name="dateFilter"><see cref="MyCompany.Visitors.Client.IVisitService"/></param>
        /// <returns><see cref="MyCompany.Visitors.Client.IVisitService"/></returns>
        public async Task<IList<Visit>> GetUserVisits(string filter, PictureType pictureType, int pageSize, int pageCount, DateTime dateFilter)
        {
            string url = String.Format(CultureInfo.InvariantCulture
              , "{0}api/visits/user?filter={1}&pictureType={2}&pageSize={3}&pageCount={4}&dateFilter={5}", _urlPrefix, filter, (int)pictureType, pageSize, pageCount, dateFilter);

            return await base.GetAsync<IList<Visit>>(url);
        }
Beispiel #8
0
        /**
         * Return the dimension of this image
         *
         * @param is the stream Containing the image data
         * @param type type of the picture: {@link NPOI.SS.UserModel.Workbook#PICTURE_TYPE_JPEG},
         * {@link NPOI.SS.UserModel.Workbook#PICTURE_TYPE_PNG} or {@link NPOI.SS.UserModel.Workbook#PICTURE_TYPE_DIB}
         *
         * @return image dimension in pixels
         */
        public static Size GetImageDimension(Stream is1, PictureType type)
        {
            Size size = new Size();

            if (type == PictureType.JPEG || type == PictureType.PNG || type == PictureType.DIB)
            {
                //we can calculate the preferred size only for JPEG, PNG and BMP
                //other formats like WMF, EMF and PICT are not supported in Java
                using (Image img = Image.FromStream(is1))
                {
                    int[] dpi = GetResolution(img);

                    //if DPI is zero then assume standard 96 DPI
                    //since cannot divide by zero
                    if (dpi[0] == 0) dpi[0] = PIXEL_DPI;
                    if (dpi[1] == 0) dpi[1] = PIXEL_DPI;

                    size.Width = img.Width * PIXEL_DPI / dpi[0];
                    size.Height = img.Height * PIXEL_DPI / dpi[1];
                    return size;
                }
            }
            else
                logger.Log(POILogger.WARN, "Only JPEG, PNG and DIB pictures can be automatically sized");
            return size;
        }
 public override void Read(BitReader bitReader)
 {
     base.Read(bitReader);
       PrimaryPicType = (PictureType)bitReader.GetByteFromNBits(3);
       bitReader.DiscardTrailingBits(); // complete the byte
       while (MoreRBSPData(bitReader))
     bitReader.ReadByte();
 }
Beispiel #10
0
 /// <summary>
 /// Creates a new instance of PictureFrame.
 /// </summary>
 /// <param name="encoding">the text encoding</param>
 /// <param name="mimeType">the MIME type</param>
 /// <param name="description">the description</param>
 /// <param name="picture">the picture type</param>
 /// <param name="data">the picture bytes</param>
 public PictureFrame(TextEncodingType encoding, string mimeType, string description, PictureType picture,
                     byte[] data)
 {
     TextEncoding = encoding;
     MimeType = mimeType;
     Description = description;
     PictureCoding = picture;
     PictureData = data;
 }
Beispiel #11
0
		/// <summary>
		/// Creates a new instance of PictureFrame.
		/// </summary>
		/// <param name="encoding">the text encoding</param>
		/// <param name="mimeType">the MIME type</param>
		/// <param name="description">the description</param>
		/// <param name="picture">the picture type</param>
		/// <param name="data">the picture bytes</param>
		public PictureFrame(Encoding encoding, string mimeType, string description, PictureType picture, byte[] data)
		{
		    Descriptor.ID = "APIC";
			TextEncoding = encoding;
			MimeType = mimeType;
			Description = description;
			PictureCoding = picture;
			PictureData = data;
		}
Beispiel #12
0
 public PictureFrame(byte[] raw_data, System.Drawing.Image image, string description, PictureType pictureType)
     : this(image, description, pictureType)
 {
     if(raw_data==null)
     {
         throw new ArgumentNullException("The passed image raw data can not be null.");
     }
     this._rawData = raw_data;
 }
Beispiel #13
0
 public PictureFrame(System.Drawing.Image image, string description, PictureType pictureType)
     : this(description, pictureType)
 {
     if(image==null)
     {
         throw new ArgumentNullException("The passed image object can not be null.");
     }
     this._image=image;
 }
Beispiel #14
0
 /// <summary>
 /// Creates a new instance of PictureFrame.
 /// </summary>
 /// <param name="encoding">the text encoding</param>
 /// <param name="mimeType">the MIME type</param>
 /// <param name="description">the description</param>
 /// <param name="picture">the picture type</param>
 /// <param name="data">the picture bytes</param>
 public PictureFrame(Encoding encoding, string mimeType, string description, PictureType picture,
                     IList<byte> data)
 {
     Descriptor.Id = "APIC";
     TextEncoding = encoding;
     MimeType = mimeType;
     Description = description;
     PictureCoding = picture;
     PictureData = new ReadOnlyCollection<byte>(data);
 }
 public static string GetStringFromPictureType(PictureType pictureType)
 {
     foreach (KeyValuePair<string, PictureType> pair1 in PictureTypeHelper.m_PictureTypeDictionary)
     {
         if (((PictureType) pair1.Value) == pictureType)
         {
             return pair1.Key;
         }
     }
     return "Other";
 }
 public AttachedPictureFrame(IPicture picture) : base(FrameType.APIC, 4)
 {
     this.text_encoding = TagLib.Id3v2.Tag.DefaultEncoding;
     if (picture == null)
     {
         throw new ArgumentNullException("picture");
     }
     this.mime_type = picture.MimeType;
     this.type = picture.Type;
     this.description = picture.Description;
     this.data = picture.Data;
 }
Beispiel #17
0
        private void ParseImage(byte[] data, PictureName name, PictureType type)
        {
            Image img = Image.FromStream(new MemoryStream(data));
            if (!_images.ContainsKey(name))
            {
                _images.Add(name, new Dictionary<PictureType, Image>());
            }

            if (_images[name].ContainsKey(type))
            {
                _images[name][type] = img;
            }
            else
            {
                _images[name].Add(type, img);
            }
        }
Beispiel #18
0
 public Picture (IPicture picture)
 {
    if (picture == null)
       throw new ArgumentNullException ("picture");
    
    _type        = picture.Type;
    _mimetype    = picture.MimeType;
    _description = picture.Description;
    _data        = picture.Data;
    
    TagLib.Flac.Picture flac_picture = picture as TagLib.Flac.Picture;
    if (flac_picture != null)
    {
       _width          = flac_picture.Width;
       _height         = flac_picture.Height;
       _color_depth    = flac_picture.ColorDepth;
       _indexed_colors = flac_picture.IndexedColors;
    }
 }
 public Picture(IPicture picture)
 {
     if (picture == null)
     {
         throw new ArgumentNullException("picture");
     }
     this.type = picture.Type;
     this.mime_type = picture.MimeType;
     this.description = picture.Description;
     this.picture_data = picture.Data;
     TagLib.Flac.Picture picture2 = picture as TagLib.Flac.Picture;
     if (picture2 != null)
     {
         this.width = picture2.Width;
         this.height = picture2.Height;
         this.color_depth = picture2.ColorDepth;
         this.indexed_colors = picture2.IndexedColors;
     }
 }
Beispiel #20
0
 public Picture (ByteVector data)
 {
    if (data == null)
       throw new ArgumentNullException ("data");
    
    if (data.Count < 32)
       throw new CorruptFileException ("Data must be at least 32 bytes long");
    
    int pos = 0;
    _type = (PictureType) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    int mimetype_length = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    _mimetype = data.ToString (StringType.Latin1, pos, mimetype_length);
    pos += mimetype_length;
    
    int description_length = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    _description = data.ToString (StringType.UTF8, pos, description_length);
    pos += description_length;
    
    _width = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    _height = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    _color_depth = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    _indexed_colors = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    int data_length = (int) data.Mid (pos, 4).ToUInt ();
    pos += 4;
    
    _data = data.Mid (pos, data_length);
 }
Beispiel #21
0
 public PictureFrame(string fileName, string description, PictureType pictureType)
     : this(description, pictureType)
 {
     this._image = System.Drawing.Image.FromFile(fileName);
 }
        /// <summary>
        ///    Performs the actual parsing of the raw data.
        /// </summary>
        /// <remarks>
        ///    Because of the high parsing cost and relatively low usage
        ///    of the class, <see cref="ParseFields" /> only stores the
        ///    field data so it can be parsed on demand. Whenever a
        ///    property or method is called which requires the data,
        ///    this method is called, and only on the first call does it
        ///    actually parse the data.
        /// </remarks>
        protected void ParseRawData()
        {
            if (raw_data == null)
            {
                return;
            }

            int pos = 0;
            int offset;

            text_encoding = (StringType)raw_data [pos++];

            if (raw_version > 2)
            {
                offset = raw_data.Find(ByteVector.TextDelimiter(
                                           StringType.Latin1), pos);

                if (offset < pos)
                {
                    return;
                }

                mime_type = raw_data.ToString(
                    StringType.Latin1, pos, offset - pos);
                pos = offset + 1;
            }
            else
            {
                ByteVector ext = raw_data.Mid(pos, 3);

                if (ext == "JPG")
                {
                    mime_type = "image/jpeg";
                }
                else if (ext == "PNG")
                {
                    mime_type = "image/png";
                }
                else
                {
                    mime_type = "image/unknown";
                }

                pos += 3;
            }

            ByteVector delim = ByteVector.TextDelimiter(
                text_encoding);

            type = (PictureType)raw_data [pos++];

            offset = raw_data.Find(delim, pos, delim.Count);

            if (offset < pos)
            {
                return;
            }

            description = raw_data.ToString(text_encoding, pos,
                                            offset - pos);
            pos = offset + delim.Count;
            raw_data.RemoveRange(0, pos);
            this.data = raw_data;

            this.raw_data = null;
        }
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual string GetPictureUrl(Picture picture,
                                            int targetSize                 = 0,
                                            bool showDefaultPicture        = true,
                                            string storeLocation           = null,
                                            PictureType defaultPictureType = PictureType.Entity)
        {
            string url = string.Empty;

            byte[] pictureBinary = null;
            if (picture != null)
            {
                pictureBinary = LoadPictureBinary(picture);
            }
            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
                }
                return(url);
            }

            string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (picture.IsNew)
            {
                DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = UpdatePicture(picture.Id,
                                        pictureBinary,
                                        picture.MimeType,
                                        picture.SeoFilename,
                                        picture.AltAttribute,
                                        picture.TitleAttribute,
                                        false,
                                        false);
            }
            lock (s_lock)
            {
                string seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure
                if (targetSize == 0)
                {
                    //original size (no resizing required)
                    thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
                                    string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), seoFileName, lastPart) :
                                    string.Format("{0}.{1}", picture.Id.ToString("0000000"), lastPart);
                    var thumbFilePath = GetThumbLocalPath(thumbFileName);
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        SaveThumb(thumbFilePath, thumbFileName, pictureBinary);
                    }
                }
                else
                {
                    //resizing required
                    thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
                                    string.Format("{0}_{1}_{2}.{3}", picture.Id.ToString("0000000"), seoFileName, targetSize, lastPart) :
                                    string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), targetSize, lastPart);
                    var thumbFilePath = GetThumbLocalPath(thumbFileName);
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        using (var stream = new MemoryStream(pictureBinary))
                        {
                            Bitmap b = null;
                            try
                            {
                                //try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
                                b = new Bitmap(stream);
                            }
                            catch (ArgumentException exc)
                            {
                                _logger.Error(string.Format("Error generating picture thumb. ID={0}", picture.Id), exc);
                            }
                            if (b == null)
                            {
                                //bitmap could not be loaded for some reasons
                                return(url);
                            }

                            using (var destStream = new MemoryStream())
                            {
                                var newSize = CalculateDimensions(b.Size, targetSize);
                                ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                                {
                                    Width   = newSize.Width,
                                    Height  = newSize.Height,
                                    Scale   = ScaleMode.Both,
                                    Quality = _mediaSettings.DefaultImageQuality
                                });
                                var destBinary = destStream.ToArray();
                                SaveThumb(thumbFilePath, thumbFileName, destBinary);
                                b.Dispose();
                            }
                        }
                    }
                }
            }
            url = GetThumbUrl(thumbFileName, storeLocation);
            return(url);
        }
Beispiel #24
0
        /// <summary>
        /// 将图像数据根据指定模板,绘制到指定路径的Excel文件中
        /// </summary>
        /// <param name="filePath">操作的文件的路径</param>
        /// <param name="template">模板对象</param>
        /// <param name="graphDatas">图像数据的集合</param>
        public void DrawGraphsCollection(String filePath, ExcelDataExtractTemplate template, Byte[][] graphDatas, PictureType type = DefaultPictureType)
        {
            IWorkbook workBook = this.OpenExcel(filePath);
            ISheet    sheet    = this.OpenSheet(workBook, template.SheetNum);

            this.DrawGraphsCollection(workBook, sheet, template, graphDatas, type);
            File.Delete(filePath);
            using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                workBook.Write(stream);
            }
        }
Beispiel #25
0
 public string GetPictureUrl(string pictureId, int targetSize = 0, PictureType defaultPictureType = PictureType.Post)
 {
     throw new NotImplementedException();
 }
Beispiel #26
0
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="siteLocation">Site location URL; null to use determine the current site location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual string GetPictureUrl(Picture picture,
                                            int targetSize                 = 0,
                                            bool showDefaultPicture        = true,
                                            string siteLocation            = null,
                                            PictureType defaultPictureType = PictureType.Entity)
        {
            var url = string.Empty;

            byte[] pictureBinary = null;
            if (picture != null)
            {
                pictureBinary = LoadPictureBinary(picture);
            }
            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType, siteLocation);
                }
                return(url);
            }

            if (picture.IsNew)
            {
                DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = UpdatePicture(picture.Id,
                                        pictureBinary,
                                        picture.MimeType,
                                        picture.SeoFilename,
                                        picture.AltAttribute,
                                        picture.TitleAttribute,
                                        false,
                                        false);
            }

            var seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure

            var    lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (targetSize == 0)
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName)
                    ? $"{picture.Id:0000000}_{seoFileName}.{lastPart}"
                    : $"{picture.Id:0000000}.{lastPart}";
            }
            else
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName)
                    ? $"{picture.Id:0000000}_{seoFileName}_{targetSize}.{lastPart}"
                    : $"{picture.Id:0000000}_{targetSize}.{lastPart}";
            }
            var thumbFilePath = GetThumbLocalPath(thumbFileName);

            //the named mutex helps to avoid creating the same files in different threads,
            //and does not decrease performance significantly, because the code is blocked only for the specific file.
            using (var mutex = new Mutex(false, thumbFileName))
            {
                if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    mutex.WaitOne();

                    //check, if the file was created, while we were waiting for the release of the mutex.
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        byte[] pictureBinaryResized;
                        if (targetSize != 0)
                        {
                            //resizing required
                            using (var image = Image.Load(pictureBinary, out var imageFormat))
                            {
                                image.Mutate(imageProcess => imageProcess.Resize(new ResizeOptions
                                {
                                    Mode = ResizeMode.Max,
                                    Size = CalculateDimensions(image.Size(), targetSize)
                                }));

                                pictureBinaryResized = EncodeImage(image, imageFormat);
                            }
                        }
                        else
                        {
                            //create a copy of pictureBinary
                            pictureBinaryResized = pictureBinary.ToArray();
                        }

                        SaveThumb(thumbFilePath, thumbFileName, picture.MimeType, pictureBinaryResized);
                    }

                    mutex.ReleaseMutex();
                }
            }
            url = GetThumbUrl(thumbFileName, siteLocation);
            return(url);
        }
Beispiel #27
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/>
        /// </summary>
        /// <param name="filter"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="pageSize"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="pageCount"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="dateFilter"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <returns></returns>
        public async Task <IEnumerable <Visit> > GetVisitsFromDateAsync(string filter, PictureType pictureType, int pageSize, int pageCount, DateTime dateFilter)
        {
            dateFilter = DateTime.SpecifyKind(dateFilter, DateTimeKind.Utc);

            var results = await _context.Visits
                          .Where(q => String.IsNullOrEmpty(filter) || q.Comments.Contains(filter) || (q.Visitor.FirstName + " " + q.Visitor.LastName).Contains(filter) || (q.Visitor.Email.Contains(filter)))
                          .Where(q => q.VisitDateTime >= dateFilter)
                          .Select(v => new
            {
                Visit            = v,
                Visitor          = v.Visitor,
                VisitorImages    = v.Visitor.VisitorPictures.Where(vp => vp.PictureType == pictureType),
                Employee         = v.Employee,
                EmployeePictures = v.Employee.EmployeePictures.Where(ep => ep.PictureType == pictureType)
            })
                          .OrderBy(v => v.Visit.VisitDateTime)
                          .Skip(pageSize * pageCount)
                          .Take(pageSize)
                          .ToListAsync();

            return(results.Select(v => BuildVisit(v.Visit)));
        }
Beispiel #28
0
 public AttachedPicture()
 {
     _pictureType = PictureType.CoverFront;
 }
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <returns>Picture URL</returns>
        public virtual string GetDefaultPictureUrl(int targetSize = 0, 
            PictureType defaultPictureType = PictureType.Entity,
            string storeLocation = null)
        {
            string defaultImageFileName;
            switch (defaultPictureType)
            {
                case PictureType.Avatar:
                    defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
                    break;
                case PictureType.Entity:
                default:
                    defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image2.png");
                    break;
            }

            string filePath = GetPictureLocalPath(defaultImageFileName,
                imagesDirectoryPath: _settingService.GetSettingByKey<string>("Media.DefaultImageDirectoryPath"));

            if (!File.Exists(filePath))
            {
                return "";
            }
            if (targetSize == 0)
            {
                string url = (!String.IsNullOrEmpty(storeLocation)
                                 ? storeLocation
                                 : _webHelper.GetStoreLocation())
                                 + "content/images/" + defaultImageFileName;
                return url;
            }
            else
            {
                string fileExtension = Path.GetExtension(filePath);
                string thumbFileName = string.Format("{0}_{1}{2}",
                    Path.GetFileNameWithoutExtension(filePath),
                    targetSize,
                    fileExtension);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);
                if (!File.Exists(thumbFilePath))
                {
                    using (var b = new Bitmap(filePath))
                    {
                        using (var destStream = new MemoryStream())
                        {
                            var newSize = CalculateDimensions(b.Size, targetSize);
                            ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                            {
                                Width = newSize.Width,
                                Height = newSize.Height,
                                Scale = ScaleMode.Both,
                                Quality = _mediaSettings.DefaultImageQuality
                            });
                            var destBinary = destStream.ToArray();
                            File.WriteAllBytes(thumbFilePath, destBinary);
                        }
                    }
                }
                var url = GetThumbUrl(thumbFileName, storeLocation);
                return url;
            }
        }
Beispiel #30
0
 public int AddPicture(byte[] pictureData, PictureType format)
 {
     return(XssfWorkbook.AddPicture(pictureData, format));
 }
Beispiel #31
0
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual async Task <string> GetPictureUrl(Picture picture,
                                                         int targetSize                 = 0,
                                                         bool showDefaultPicture        = true,
                                                         string storeLocation           = null,
                                                         PictureType defaultPictureType = PictureType.Entity)
        {
            if (picture == null)
            {
                return(showDefaultPicture ? await GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation) : string.Empty);
            }

            byte[] pictureBinary = null;

            if (picture.IsNew)
            {
                if ((picture.PictureBinary?.Length ?? 0) == 0)
                {
                    pictureBinary = await LoadPictureBinary(picture);
                }
                else
                {
                    pictureBinary = picture.PictureBinary;
                }

                await DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = await UpdatePicture(picture.Id,
                                              pictureBinary,
                                              picture.MimeType,
                                              picture.SeoFilename,
                                              picture.AltAttribute,
                                              picture.TitleAttribute,
                                              false,
                                              false);
            }

            string seoFileName = picture.SeoFilename;
            string lastPart    = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (targetSize == 0)
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName) ?
                                string.Format("{0}_{1}.{2}", picture.Id, seoFileName, lastPart) :
                                string.Format("{0}.{1}", picture.Id, lastPart);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);

                if (await GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    return(GetThumbUrl(thumbFileName, storeLocation));
                }

                pictureBinary = pictureBinary ?? await LoadPictureBinary(picture);

                using (var mutex = new Mutex(false, thumbFileName))
                {
                    mutex.WaitOne();

                    await SaveThumb(thumbFilePath, thumbFileName, pictureBinary);

                    mutex.ReleaseMutex();
                }
            }
            else
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName) ?
                                string.Format("{0}_{1}_{2}.{3}", picture.Id, seoFileName, targetSize, lastPart) :
                                string.Format("{0}_{1}.{2}", picture.Id, targetSize, lastPart);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);

                if (await GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    return(GetThumbUrl(thumbFileName, storeLocation));
                }

                pictureBinary = pictureBinary ?? await LoadPictureBinary(picture);

                using (var mutex = new Mutex(false, thumbFileName))
                {
                    mutex.WaitOne();
                    if (pictureBinary != null)
                    {
                        try
                        {
                            using (var image = SKBitmap.Decode(pictureBinary))
                            {
                                pictureBinary = ApplyResize(image, EncodedImageFormat(picture.MimeType), targetSize);
                            }
                        }
                        catch { }
                    }
                    await SaveThumb(thumbFilePath, thumbFileName, pictureBinary);

                    mutex.ReleaseMutex();
                }
            }
            return(GetThumbUrl(thumbFileName, storeLocation));
        }
Beispiel #32
0
        public async Task <IDataResult <ImageUploadedDto> > Upload(string name, IFormFile pictureFile, PictureType pictureType, string folderName = null)
        {
            /* Eğer folderName değişkeni null gelir ise, o zaman resim tipine göre (PictureType) klasör adı ataması yapılır. */
            folderName ??= pictureType == PictureType.User ? userImagesFolder : postImagesFolder;

            /* Eğer folderName değişkeni ile gelen klasör adı sistemimizde mevcut değilse, yeni bir klasör oluşturulur. */
            if (!Directory.Exists($"{_wwwroot}/{imgFolder}/{folderName}"))
            {
                Directory.CreateDirectory($"{_wwwroot}/{imgFolder}/{folderName}");
            }

            /* Resimin yüklenme sırasındaki ilk adı oldFileName adlı değişkene atanır. */
            string oldFileName = Path.GetFileNameWithoutExtension(pictureFile.FileName);

            /* Resimin uzantısı fileExtension adlı değişkene atanır. */
            string fileExtension = Path.GetExtension(pictureFile.FileName);

            Regex regex = new("[*'\",._&#^@]");

            name = regex.Replace(name, string.Empty);


            DateTime dateTime = DateTime.Now;

            /*
             * // Parametre ile gelen değerler kullanılarak yeni bir resim adı oluşturulur.
             * // Örn: CanturkAtas_587_5_38_12_3_10_2020.png
             */
            string newFileName = $"{name}_{dateTime.FullDateTimeStringWithUnderscore()}{fileExtension}";

            /* Kendi parametrelerimiz ile sistemimize uygun yeni bir dosya yolu (path) oluşturulur. */
            var path = Path.Combine($"{_wwwroot}/{imgFolder}/{folderName}", newFileName);

            /* Sistemimiz için oluşturulan yeni dosya yoluna resim kopyalanır. */
            await using (var stream = new FileStream(path, FileMode.Create))
            {
                await pictureFile.CopyToAsync(stream);
            }

            /* Resim tipine göre kullanıcı için bir mesaj oluşturulur. */
            string nameMessage = pictureType == PictureType.User
                ? $"{name} adlı kullanıcının resimi başarıyla yüklenmiştir."
                : $"{name} adlı makalenin resimi başarıyla yüklenmiştir.";

            return(new DataResult <ImageUploadedDto>(ResultStatus.Success, nameMessage, new ImageUploadedDto
            {
                FullName = $"{folderName}/{newFileName}",
                OldName = oldFileName,
                Extension = fileExtension,
                FolderName = folderName,
                Path = path,
                Size = pictureFile.Length
            }));
        }
Beispiel #33
0
 public PictureFrame(byte[] raw_data, System.Drawing.Image image, string description, PictureType pictureType)
     : this(image, description, pictureType)
 {
     if (raw_data == null)
     {
         throw new ArgumentNullException("The passed image raw data can not be null.");
     }
     this._rawData = raw_data;
 }
Beispiel #34
0
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <returns>Picture URL</returns>
        public virtual async Task <string> GetDefaultPictureUrl(int targetSize = 0,
                                                                PictureType defaultPictureType = PictureType.Entity,
                                                                string storeLocation           = null)
        {
            string defaultImageFileName;

            switch (defaultPictureType)
            {
            case PictureType.Avatar:
                defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
                break;

            case PictureType.Entity:
            default:
                defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.png");
                break;
            }

            string filePath = GetPictureLocalPath(defaultImageFileName);

            if (!File.Exists(filePath))
            {
                return("");
            }
            if (targetSize == 0)
            {
                string url = (!string.IsNullOrEmpty(storeLocation)
                                 ? storeLocation
                                 : _webHelper.GetStoreLocation())
                             + "content/images/" + defaultImageFileName;
                return(url);
            }
            else
            {
                string fileExtension = Path.GetExtension(filePath);
                string thumbFileName = string.Format("{0}_{1}{2}",
                                                     Path.GetFileNameWithoutExtension(filePath),
                                                     targetSize,
                                                     fileExtension);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);

                using (var mutex = new Mutex(false, thumbFileName))
                {
                    if (GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        return(GetThumbUrl(thumbFileName, storeLocation));
                    }

                    mutex.WaitOne();
                    using (var image = new MagickImage(filePath))
                    {
                        var pictureBinary = File.ReadAllBytes(filePath);
                        pictureBinary = await ApplyResize(image, targetSize);

                        SaveThumb(thumbFilePath, thumbFileName, pictureBinary);
                    }
                    mutex.ReleaseMutex();
                }
                var url = GetThumbUrl(thumbFileName, storeLocation);
                return(url);
            }
        }
Beispiel #35
0
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <returns>Picture URL</returns>
        public virtual async Task <string> GetDefaultPictureUrl(int targetSize = 0,
                                                                PictureType defaultPictureType = PictureType.Entity,
                                                                string storeLocation           = null)
        {
            string defaultImageFileName;

            switch (defaultPictureType)
            {
            case PictureType.Avatar:
                defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
                break;

            case PictureType.Entity:
            default:
                defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.png");
                break;
            }

            string filePath = GetPictureLocalPath(defaultImageFileName);

            if (!File.Exists(filePath))
            {
                return("");
            }
            if (targetSize == 0)
            {
                return(!string.IsNullOrEmpty(storeLocation)
                        ? storeLocation
                        : string.IsNullOrEmpty(_mediaSettings.StoreLocation) ?
                       _storeContext.CurrentStore.SslEnabled ? _storeContext.CurrentStore.SecureUrl : _storeContext.CurrentStore.Url :
                       _mediaSettings.StoreLocation
                       + "content/images/" + defaultImageFileName);
            }
            else
            {
                string fileExtension = Path.GetExtension(filePath);
                string thumbFileName = string.Format("{0}_{1}{2}",
                                                     Path.GetFileNameWithoutExtension(filePath),
                                                     targetSize,
                                                     fileExtension);

                var thumbFilePath = GetThumbLocalPath(thumbFileName);

                if (await GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    return(GetThumbUrl(thumbFileName, storeLocation));
                }

                using (var mutex = new Mutex(false, thumbFileName))
                {
                    mutex.WaitOne();
                    using (var image = SKBitmap.Decode(filePath))
                    {
                        var pictureBinary = ApplyResize(image, EncodedImageFormat(fileExtension), targetSize);
                        await SaveThumb(thumbFilePath, thumbFileName, pictureBinary);
                    }
                    mutex.ReleaseMutex();
                }
                var url = GetThumbUrl(thumbFileName, storeLocation);
                return(url);
            }
        }
 public virtual string GetPictureUrl(
     int pictureId,
     int targetSize = 0,
     bool showDefaultPicture = true,
     string storeLocation = null,
     PictureType defaultPictureType = PictureType.Entity)
 {
     var picture = GetPictureById(pictureId);
     return GetPictureUrl(picture, targetSize, showDefaultPicture, storeLocation, defaultPictureType);
 }
Beispiel #37
0
        /// <summary>
        /// <see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/>
        /// </summary>
        /// <param name="employeeEmail"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="filter"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="pictureType"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="pageSize"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <param name="pageCount"><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></param>
        /// <returns><see cref="MyCompany.Visitors.Data.Repositories.IVisitRepository"/></returns>
        public async Task <IEnumerable <Visit> > GetUserVisitsAsync(string employeeEmail, string filter, PictureType pictureType, int pageSize, int pageCount)
        {
            //var dateFilter = DateTime.UtcNow.AddHours(-1);

            var result = await _context.Visits
                         .Where(q => q.Employee.Email == employeeEmail
                                &&
                                (String.IsNullOrEmpty(filter) || q.Comments.Contains(filter) || (q.Visitor.FirstName + " " + q.Visitor.LastName).Contains(filter))
                                //&&
                                //q.VisitDateTime >= dateFilter
                                )
                         .OrderBy(q => q.VisitDateTime)
                         .Select(v => new
            {
                Visit            = v,
                Visitor          = v.Visitor,
                VisitorImages    = v.Visitor.VisitorPictures.Where(vp => vp.PictureType == pictureType),
                Employee         = v.Employee,
                EmployeePictures = v.Employee.EmployeePictures.Where(ep => ep.PictureType == pictureType)
            })
                         .Skip(pageSize * pageCount)
                         .Take(pageSize)
                         .ToListAsync();


            return(result.Select(v => BuildVisit(v.Visit)));
        }
        private string GetDefaultImageFileName(PictureType defaultPictureType = PictureType.Entity)
        {
            string defaultImageFileName;
            switch (defaultPictureType)
            {
                case PictureType.Entity:
                    defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.jpg");
                    break;
                case PictureType.Avatar:
                    defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
                    break;
                default:
                    defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.jpg");
                    break;
            }

            return defaultImageFileName;
        }
Beispiel #39
0
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual string GetPictureUrl(Picture picture,
                                            int targetSize                 = 0,
                                            bool showDefaultPicture        = true,
                                            string storeLocation           = null,
                                            PictureType defaultPictureType = PictureType.Entity)
        {
            string url = string.Empty;

            byte[] pictureBinary = null;
            if (picture != null)
            {
                pictureBinary = LoadPictureBinary(picture);
            }
            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
                }
                return(url);
            }

            if (picture.IsNew)
            {
                DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = UpdatePicture(picture.Id,
                                        pictureBinary,
                                        picture.MimeType,
                                        picture.SeoFilename,
                                        picture.AltAttribute,
                                        picture.TitleAttribute,
                                        false,
                                        false);
            }

            var seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure

            string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (targetSize == 0)
            {
                thumbFileName = !String.IsNullOrEmpty(seoFileName)
                    ? string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), seoFileName, lastPart)
                    : string.Format("{0}.{1}", picture.Id.ToString("0000000"), lastPart);
            }
            else
            {
                thumbFileName = !String.IsNullOrEmpty(seoFileName)
                    ? string.Format("{0}_{1}_{2}.{3}", picture.Id.ToString("0000000"), seoFileName, targetSize, lastPart)
                    : string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), targetSize, lastPart);
            }
            string thumbFilePath = GetThumbLocalPath(thumbFileName);

            //the named mutex helps to avoid creating the same files in different threads,
            //and does not decrease performance significantly, because the code is blocked only for the specific file.
            using (var mutex = new Mutex(false, thumbFileName))
            {
                if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    mutex.WaitOne();

                    //check, if the file was created, while we were waiting for the release of the mutex.
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        byte[] pictureBinaryResized;

                        //resizing required
                        if (targetSize != 0)
                        {
                            using (var stream = new MemoryStream(pictureBinary))
                            {
                                Bitmap b = null;
                                try
                                {
                                    //try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
                                    b = new Bitmap(stream);
                                }
                                catch (ArgumentException exc)
                                {
                                    _logger.Error(string.Format("Error generating picture thumb. ID={0}", picture.Id),
                                                  exc);
                                }

                                if (b == null)
                                {
                                    //bitmap could not be loaded for some reasons
                                    return(url);
                                }

                                using (var destStream = new MemoryStream())
                                {
                                    var newSize = CalculateDimensions(b.Size, targetSize);
                                    ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                                    {
                                        Width   = newSize.Width,
                                        Height  = newSize.Height,
                                        Scale   = ScaleMode.Both,
                                        Quality = _mediaSettings.DefaultImageQuality
                                    });
                                    pictureBinaryResized = destStream.ToArray();
                                    b.Dispose();
                                }
                            }
                        }
                        else
                        {
                            //create a copy of pictureBinary
                            pictureBinaryResized = pictureBinary.ToArray();
                        }

                        SaveThumb(thumbFilePath, thumbFileName, picture.MimeType, pictureBinaryResized);
                    }

                    mutex.ReleaseMutex();
                }
            }
            url = GetThumbUrl(thumbFileName, storeLocation);
            return(url);
        }
Beispiel #40
0
 public void Reset(IPicture picture)
 {
     Source = picture.Source;
     Name   = picture.Name;
     Type   = picture.Type;
 }
Beispiel #41
0
 ///<summary>Sets the value of the <c>&lt;PictureSource&gt;</c> element.</summary>
 /// <param name="Type">The way the picture is specified.</param>
 /// <param name="Value">Gets or sets the content value of the &amp;lt;PictureSource&amp;gt; element</param>
 ///<remarks>
 /// <para>This form of <c>setPictureSource</c> is provided as a convenience method
 /// that is functionally equivalent to the <c>PictureSource</c></para>
 /// <para>Version: 2.6</para>
 /// <para>Since: 1.1</para>
 /// </remarks>
 public void SetPictureSource(PictureType Type, string Value)
 {
     RemoveChild(StudentDTD.STUDENTPICTURE_PICTURESOURCE);
     AddChild(StudentDTD.STUDENTPICTURE_PICTURESOURCE, new PictureSource(Type, Value));
 }
Beispiel #42
0
 public async Task <Visit> Get(int visitId, PictureType pictureType)
 {
     return(await _visitRepository.GetCompleteInfoAsync(visitId, pictureType));
 }
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <returns>Picture URL</returns>
        public virtual string GetDefaultPictureUrl(int targetSize = 0,
                                                   PictureType defaultPictureType = PictureType.Entity,
                                                   string storeLocation           = null)
        {
            string defaultImageFileName;

            switch (defaultPictureType)
            {
            case PictureType.Avatar:
                defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
                break;

            case PictureType.Entity:
            default:
                defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.png");
                break;
            }
            string filePath = GetPictureLocalPath(defaultImageFileName);

            if (!File.Exists(filePath))
            {
                return("");
            }


            if (targetSize == 0)
            {
                string url = (!String.IsNullOrEmpty(storeLocation)
                                 ? storeLocation
                                 : _webHelper.GetStoreLocation())
                             + "content/images/" + defaultImageFileName;
                return(url);
            }
            else
            {
                string fileExtension = Path.GetExtension(filePath);
                string thumbFileName = string.Format("{0}_{1}{2}",
                                                     Path.GetFileNameWithoutExtension(filePath),
                                                     targetSize,
                                                     fileExtension);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);
                if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    using (var b = new Bitmap(filePath))
                    {
                        using (var destStream = new MemoryStream())
                        {
                            var newSize = CalculateDimensions(b.Size, targetSize);
                            ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                            {
                                Width   = newSize.Width,
                                Height  = newSize.Height,
                                Scale   = ScaleMode.Both,
                                Quality = _mediaSettings.DefaultImageQuality
                            });
                            var destBinary = destStream.ToArray();
                            SaveThumb(thumbFilePath, thumbFileName, destBinary);
                        }
                    }
                }
                var url = GetThumbUrl(thumbFileName, storeLocation);
                return(url);
            }
        }
Beispiel #44
0
 public async Task <IEnumerable <Visit> > GetVisitsFromDate(string filter, PictureType pictureType, int pageSize, int pageCount, DateTimeOffset dateFilter)
 {
     return(await _visitRepository.GetVisitsFromDateAsync(filter, pictureType, pageSize, pageCount, dateFilter.DateTime));
 }
 /// <summary>
 ///    Gets a specified picture frame from the specified tag,
 ///    optionally creating it if it does not exist.
 /// </summary>
 /// <param name="tag">
 ///    A <see cref="Tag" /> object to search in.
 /// </param>
 /// <param name="type">
 ///    A <see cref="PictureType" /> specifying the picture type
 ///    to match.
 /// </param>
 /// <param name="create">
 ///    A <see cref="bool" /> specifying whether or not to create
 ///    and add a new frame to the tag if a match is not found.
 /// </param>
 /// <returns>
 ///    A <see cref="AttachedPictureFrame" /> object containing
 ///    the matching frame, or <see langword="null" /> if a match
 ///    wasn't found and <paramref name="create" /> is <see
 ///    langword="false" />.
 /// </returns>
 public static AttachedPictureFrame Get(Tag tag,
                                        PictureType type,
                                        bool create)
 {
     return(Get(tag, null, type, create));
 }
Beispiel #46
0
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual async Task <string> GetPictureUrl(Picture picture,
                                                         int targetSize                 = 0,
                                                         bool showDefaultPicture        = true,
                                                         string storeLocation           = null,
                                                         PictureType defaultPictureType = PictureType.Entity)
        {
            string url = string.Empty;

            byte[] pictureBinary = null;
            if (picture != null)
            {
                pictureBinary = await LoadPictureBinary(picture);
            }

            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    url = await GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
                }
                return(url);
            }

            string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (picture.IsNew)
            {
                DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = await UpdatePicture(picture.Id,
                                              pictureBinary,
                                              picture.MimeType,
                                              picture.SeoFilename,
                                              picture.AltAttribute,
                                              picture.TitleAttribute,
                                              false,
                                              false);
            }

            string seoFileName = picture.SeoFilename;

            if (targetSize == 0)
            {
                thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
                                string.Format("{0}_{1}.{2}", picture.Id, seoFileName, lastPart) :
                                string.Format("{0}.{1}", picture.Id, lastPart);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);
                using (var mutex = new System.Threading.Mutex(false, thumbFileName))
                {
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        mutex.WaitOne();
                        SaveThumb(thumbFilePath, thumbFileName, pictureBinary);
                        mutex.ReleaseMutex();
                    }
                }
            }
            else
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName) ?
                                string.Format("{0}_{1}_{2}.{3}", picture.Id, seoFileName, targetSize, lastPart) :
                                string.Format("{0}_{1}.{2}", picture.Id, targetSize, lastPart);
                var thumbFilePath = GetThumbLocalPath(thumbFileName);
                using (var mutex = new Mutex(false, thumbFileName))
                {
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        mutex.WaitOne();
                        using (var image = new MagickImage(pictureBinary))
                        {
                            var size = CalculateDimensions(image, targetSize);
                            size.IgnoreAspectRatio = true;
                            image.Resize(size);
                            pictureBinary = image.ToByteArray();
                        }
                        SaveThumb(thumbFilePath, thumbFileName, pictureBinary);
                        mutex.ReleaseMutex();
                    }
                }
            }
            url = GetThumbUrl(thumbFileName, storeLocation);
            return(url);
        }
Beispiel #47
0
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns></returns>
        public virtual string GetDefaultPictureUrl(int targetSize = 0, PictureType defaultPictureType = PictureType.Entity)
        {
            string defaultImageName;
            switch (defaultPictureType)
            {
                case PictureType.Entity:
                    defaultImageName = _settingService.GetSettingByKey("Media.DefaultImageName", "noDefaultImage.gif");
                    break;
                case PictureType.Avatar:
                    defaultImageName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "defaultAvatar.jpg");
                    break;
                default:
                    defaultImageName = _settingService.GetSettingByKey("Media.DefaultImageName", "noDefaultImage.gif");
                    break;
            }

            string relPath = _webHelper.GetStoreLocation() + "content/images/" + defaultImageName;
            if (targetSize == 0)
                return relPath;
            else
            {
                string filePath = Path.Combine(LocalImagePath, defaultImageName);
                if (File.Exists(filePath))
                {
                    string fileExtension = Path.GetExtension(filePath);
                    string fname = string.Format("{0}_{1}{2}",
                        Path.GetFileNameWithoutExtension(filePath),
                        targetSize,
                        fileExtension);
                    if (!File.Exists(Path.Combine(LocalThumbImagePath, fname)))
                    {
                        var b = new Bitmap(filePath);

                        var newSize = CalculateDimensions(b.Size, targetSize);

                        if (newSize.Width < 1)
                            newSize.Width = 1;
                        if (newSize.Height < 1)
                            newSize.Height = 1;

                        var newBitMap = new Bitmap(newSize.Width, newSize.Height);
                        var g = Graphics.FromImage(newBitMap);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        g.DrawImage(b, 0, 0, newSize.Width, newSize.Height);
                        var ep = new EncoderParameters();
                        ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, this.ImageQuality);
                        ImageCodecInfo ici = GetImageCodecInfoFromExtension(fileExtension);
                        if (ici == null)
                            ici = GetImageCodecInfoFromMimeType("image/jpeg");
                        newBitMap.Save(Path.Combine(LocalThumbImagePath, fname), ici, ep);
                        newBitMap.Dispose();
                        b.Dispose();
                    }
                    return _webHelper.GetStoreLocation() + "content/images/thumbs/" + fname;
                }
                return relPath;
            }
        }
Beispiel #48
0
 protected PictureFrame(string description, PictureType pictureType)
     : base()
 {
     this.Description = description;
     this.PictureType = pictureType;
 }
Beispiel #49
0
 internal void SetType(PictureType type) =>
 Marshal.WriteInt32(IntPtr.Add(Handle.DangerousGetHandle(),
                               Marshal.OffsetOf <PictureMetadataBlock>("Picture").ToInt32() +
                               Marshal.OffsetOf <Picture>("Type").ToInt32()), (int)type);
Beispiel #50
0
        /// <summary>
        /// Load the picture data from the file,
        /// if not done yet.
        /// </summary>
        public void Load()
        {
            // Already loaded ?
            if (data != null)
            {
                return;
            }


            // Load the picture from the stream

            Stream stream = null;

            try
            {
                if (stream_size == 0)
                {
                    data = new ByteVector();
                }
                else if (stream_size > 0)
                {
                    stream = file.ReadStream;
                    stream.Seek(stream_offset, SeekOrigin.Begin);

                    int    count = 0, read = 0, needed = (int)stream_size;
                    byte[] buffer = new byte[needed];

                    do
                    {
                        count = stream.Read(buffer, read, needed);

                        read   += count;
                        needed -= count;
                    } while (needed > 0 && count != 0);

                    data = new ByteVector(buffer, read);
                }
                else
                {
                    stream = file.ReadStream;
                    stream.Seek(stream_offset, SeekOrigin.Begin);

                    data = ByteVector.FromStream(stream);
                }
            }
            finally
            {
                // Free the resources
                if (stream != null && file != null)
                {
                    file.CloseStream(stream);
                }

                file = null;
            }

            // Retrieve remaining properties from data (if required)

            if (mime_type == null)
            {
                string ext = Picture.GetExtensionFromData(data);
                MimeType = Picture.GetMimeFromExtension(ext);
                if (ext != null)
                {
                    type = PictureType.FrontCover;
                    if (filename == null)
                    {
                        filename = description = "cover" + ext;
                    }
                }
                else
                {
                    type = PictureType.NotAPicture;
                    if (filename == null)
                    {
                        filename = "UnknownType";
                    }
                }
            }
        }
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual string GetPictureUrl(Picture picture, 
            int targetSize = 0,
            bool showDefaultPicture = true, 
            string storeLocation = null, 
            PictureType defaultPictureType = PictureType.Entity)
        {
            string url = string.Empty;
            byte[] pictureBinary = null;
            if (picture != null)
                pictureBinary = LoadPictureBinary(picture);
            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if(showDefaultPicture)
                {
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
                }
                return url;
            }

            string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;
            if (picture.IsNew)
            {
                DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = UpdatePicture(picture.Id,
                    pictureBinary,
                    picture.MimeType,
                    picture.SeoFilename,
                    picture.AltAttribute,
                    picture.TitleAttribute,
                    false,
                    false);
            }
            lock (s_lock)
            {
                string seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure
                if (targetSize == 0)
                {
                    thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
                        string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), seoFileName, lastPart) :
                        string.Format("{0}.{1}", picture.Id.ToString("0000000"), lastPart);
                    var thumbFilePath = GetThumbLocalPath(thumbFileName);
                    if (!File.Exists(thumbFilePath))
                    {
                        File.WriteAllBytes(thumbFilePath, pictureBinary);
                    }
                }
                else
                {
                    thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
                        string.Format("{0}_{1}_{2}.{3}", picture.Id.ToString("0000000"), seoFileName, targetSize, lastPart) :
                        string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), targetSize, lastPart);
                    var thumbFilePath = GetThumbLocalPath(thumbFileName);
                    if (!File.Exists(thumbFilePath))
                    {
                        using (var stream = new MemoryStream(pictureBinary))
                        {
                            Bitmap b = null;
                            try
                            {
                                //try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
                                b = new Bitmap(stream);
                            }
                            catch (ArgumentException exc)
                            {
                                _logger.Error(string.Format("Error generating picture thumb. ID={0}", picture.Id), exc);
                            }
                            if (b == null)
                            {
                                //bitmap could not be loaded for some reasons
                                return url;
                            }

                            using (var destStream = new MemoryStream())
                            {
                                var newSize = CalculateDimensions(b.Size, targetSize);
                                ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                                {
                                    Width = newSize.Width,
                                    Height = newSize.Height,
                                    Scale = ScaleMode.Both,
                                    Quality = _mediaSettings.DefaultImageQuality
                                });
                                var destBinary = destStream.ToArray();
                                File.WriteAllBytes(thumbFilePath, destBinary);
                                b.Dispose();
                            }
                        }
                    }
                }
            }
            url = GetThumbUrl(thumbFileName, storeLocation);
            return url;
        }
Beispiel #52
0
            // Travis doesn't support named semaphore, that's why we use implementation without it
            public override async Task <(string Url, Picture Picture)> GetPictureUrlAsync(Picture picture,
                                                                                          int targetSize                 = 0,
                                                                                          bool showDefaultPicture        = true,
                                                                                          string storeLocation           = null,
                                                                                          PictureType defaultPictureType = PictureType.Entity)
            {
                if (picture == null)
                {
                    return(showDefaultPicture
                        ? (await GetDefaultPictureUrlAsync(targetSize, defaultPictureType, storeLocation), null)
                        : (string.Empty, (Picture)null));
                }

                byte[] pictureBinary = null;
                if (picture.IsNew)
                {
                    await DeletePictureThumbsAsync(picture);

                    pictureBinary = await LoadPictureBinaryAsync(picture);

                    if ((pictureBinary?.Length ?? 0) == 0)
                    {
                        return(showDefaultPicture
                            ? (await GetDefaultPictureUrlAsync(targetSize, defaultPictureType, storeLocation), picture)
                            : (string.Empty, picture));
                    }

                    //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                    picture = await UpdatePictureAsync(picture.Id,
                                                       pictureBinary,
                                                       picture.MimeType,
                                                       picture.SeoFilename,
                                                       picture.AltAttribute,
                                                       picture.TitleAttribute,
                                                       false,
                                                       false);
                }

                var seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure

                var lastPart = await GetFileExtensionFromMimeTypeAsync(picture.MimeType);

                string thumbFileName;

                if (targetSize == 0)
                {
                    thumbFileName = !string.IsNullOrEmpty(seoFileName)
                        ? $"{picture.Id:0000000}_{seoFileName}.{lastPart}"
                        : $"{picture.Id:0000000}.{lastPart}";

                    var thumbFilePath = await GetThumbLocalPathAsync(thumbFileName);

                    if (await GeneratedThumbExistsAsync(thumbFilePath, thumbFileName))
                    {
                        return(await GetThumbUrlAsync(thumbFileName, storeLocation), picture);
                    }

                    pictureBinary ??= await LoadPictureBinaryAsync(picture);

                    //the named mutex helps to avoid creating the same files in different threads,
                    //and does not decrease performance significantly, because the code is blocked only for the specific file.
                    //you should be very careful, mutexes cannot be used in with the await operation
                    //we can't use semaphore here, because it produces PlatformNotSupportedException exception on UNIX based systems
                    using var mutex = new Mutex(false, thumbFileName);
                    mutex.WaitOne();
                    try
                    {
                        SaveThumbAsync(thumbFilePath, thumbFileName, string.Empty, pictureBinary).Wait();
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }
                }
                else
                {
                    thumbFileName = !string.IsNullOrEmpty(seoFileName)
                        ? $"{picture.Id:0000000}_{seoFileName}_{targetSize}.{lastPart}"
                        : $"{picture.Id:0000000}_{targetSize}.{lastPart}";

                    var thumbFilePath = await GetThumbLocalPathAsync(thumbFileName);

                    if (await GeneratedThumbExistsAsync(thumbFilePath, thumbFileName))
                    {
                        return(await GetThumbUrlAsync(thumbFileName, storeLocation), picture);
                    }

                    pictureBinary ??= await LoadPictureBinaryAsync(picture);

                    //the named mutex helps to avoid creating the same files in different threads,
                    //and does not decrease performance significantly, because the code is blocked only for the specific file.
                    //you should be very careful, mutexes cannot be used in with the await operation
                    //we can't use semaphore here, because it produces PlatformNotSupportedException exception on UNIX based systems
                    using var mutex = new Mutex(false, thumbFileName);
                    mutex.WaitOne();
                    try
                    {
                        if (pictureBinary != null)
                        {
                            try
                            {
                                using var image = SKBitmap.Decode(pictureBinary);
                                var format = GetImageFormatByMimeType(picture.MimeType);
                                pictureBinary = ImageResize(image, format, targetSize);
                            }
                            catch
                            {
                            }
                        }

                        SaveThumbAsync(thumbFilePath, thumbFileName, string.Empty, pictureBinary).Wait();
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }
                }

                return(await GetThumbUrlAsync(thumbFileName, storeLocation), picture);
            }
        public virtual string GetDefaultPictureUrl(int targetSize = 0, PictureType defaultPictureType = PictureType.Entity, string storeLocation = null)
        {
            string defaultImageFileName = GetDefaultImageFileName(defaultPictureType);

            string filePath = GetDefaultPictureLocalPath(defaultImageFileName);
            if (!File.Exists(filePath))
            {
                return string.Empty;
            }

            var url = this.GetProcessedImageUrl(
                filePath,
                0,
                Path.GetFileNameWithoutExtension(filePath),
                Path.GetExtension(filePath),
                targetSize,
                storeLocation);

            return url;
        }
Beispiel #54
0
        public void CreatePicture()
        {
            uint colorDepth = 24;
            uint colors     = 256;

            byte[]      data        = System.IO.File.ReadAllBytes(Path.Combine("Data", "testimage.png"));
            string      description = "Test Picture";
            uint        height      = 213;
            uint        width       = 400;
            PictureType pictureType = PictureType.LeadArtist;
            string      mimeType    = "image/jpeg";

            FileHelper.GetNewFile(origFile, newFile);

            using (FlacFile flac = new FlacFile(newFile))
            {
                Picture pictureBlock = new Picture();

                pictureBlock.ColorDepth  = colorDepth;
                pictureBlock.Colors      = colors;
                pictureBlock.Data        = data;
                pictureBlock.Description = description;
                pictureBlock.Height      = height;
                pictureBlock.Width       = width;
                pictureBlock.PictureType = pictureType;
                pictureBlock.MIMEType    = mimeType;

                flac.Metadata.Add(pictureBlock);

                flac.Save();
            }

            using (FlacFile flac = new FlacFile(newFile))
            {
                foreach (MetadataBlock block in flac.Metadata)
                {
                    if (block.Header.Type == MetadataBlockHeader.MetadataBlockType.Picture)
                    {
                        Picture pictureBlock = (Picture)block;

                        Assert.IsNotNull(pictureBlock);

                        Assert.AreEqual <uint>(colorDepth, pictureBlock.ColorDepth);
                        Assert.AreEqual <uint>(colors, pictureBlock.Colors);
                        Assert.AreEqual <string>(description, pictureBlock.Description);
                        Assert.AreEqual <uint>(height, pictureBlock.Height);
                        Assert.AreEqual <uint>(width, pictureBlock.Width);
                        Assert.AreEqual <PictureType>(pictureType, pictureBlock.PictureType);
                        Assert.AreEqual <string>(mimeType, pictureBlock.MIMEType);

                        bool dataIsSame = true;
                        for (int i = 0; i < data.Length; i++)
                        {
                            if (data[i] != pictureBlock.Data[i])
                            {
                                dataIsSame = false;
                                break;
                            }
                        }

                        Assert.IsTrue(dataIsSame);
                    }
                }
            }
        }
        public virtual string GetPictureUrl(
            Picture picture,
            int targetSize = 0,
            bool showDefaultPicture = true,
            string storeLocation = null,
            PictureType defaultPictureType = PictureType.Entity)
        {
            string url = string.Empty;
            byte[] pictureBinary = null;
            if (picture != null)
                pictureBinary = LoadPictureBinary(picture);
            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
                }
                return url;
            }

            if (picture.IsNew)
            {
                _imageCache.DeleteCachedImages(picture);

                // we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = UpdatePicture(picture.Id,
                    pictureBinary,
                    picture.MimeType,
                    picture.SeoFilename,
                    false,
                    false);
            }

            url = this.GetProcessedImageUrl(
                pictureBinary,
                picture.Id,
                picture.SeoFilename,
                MimeTypes.MapMimeTypeToExtension(picture.MimeType),
                targetSize,
                storeLocation);

            return url;
        }
Beispiel #56
0
        public virtual string GetPictureUrl(Picture picture, int targetSize = 0, bool showDefaultPicture = true,
                                            PictureType defaultPictureType  = PictureType.Entity)
        {
            string url = string.Empty;

            byte[] pictureBinary = null;

            if (picture != null)
            {
                pictureBinary = LoadPictureBinary(picture);
            }

            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    //返回默认图片URL
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType);
                }
                return(url);
            }

            var seoFileName = picture.SeoFilename;

            string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (targetSize == 0)
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName)
                    ? $"{picture.Id:0000000}_{seoFileName}.{lastPart}"
                    : $"{picture.Id:0000000}.{lastPart}";
            }
            else
            {
                thumbFileName = !String.IsNullOrEmpty(seoFileName)
                    ? $"{picture.Id:0000000}_{seoFileName}_{targetSize}.{lastPart}"
                    : $"{picture.Id:0000000}_{targetSize}.{lastPart}";
            }
            string thumbFilePath = GetThumbLocalPath(thumbFileName);

            using (var mutex = new Mutex(false, thumbFileName))
            {
                if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    mutex.WaitOne();

                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        byte[] pictureBinaryResized;

                        if (targetSize != 0)
                        {
                            using (var stream = new MemoryStream(pictureBinary))
                            {
                                Bitmap b = null;
                                try
                                {
                                    //try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
                                    b = new Bitmap(stream);
                                }
                                catch (ArgumentException exc)
                                {
                                    _logger.Error(string.Format("Error generating picture thumb. ID={0}", picture.Id),
                                                  exc);
                                }

                                if (b == null)
                                {
                                    //bitmap could not be loaded for some reasons
                                    return(url);
                                }

                                using (var destStream = new MemoryStream())
                                {
                                    var newSize = CalculateDimensions(b.Size, targetSize);
                                    ImageBuilder.Current.Build(b, destStream, new ResizeSettings
                                    {
                                        Width   = newSize.Width,
                                        Height  = newSize.Height,
                                        Scale   = ScaleMode.Both,
                                        Quality = _mediaSettings.DefaultImageQuality
                                    });
                                    pictureBinaryResized = destStream.ToArray();
                                    b.Dispose();
                                }
                            }
                        }
                        else
                        {
                            pictureBinaryResized = pictureBinary.ToArray();
                        }

                        SaveThumb(thumbFilePath, thumbFileName, picture.MimeType, pictureBinaryResized);
                    }

                    mutex.ReleaseMutex();
                }
            }
            url = GetThumbUrl(thumbFileName);
            return(url);
        }
Beispiel #57
0
 public static extern char av_get_pict_type_char(PictureType pict_type);
Beispiel #58
0
        public string GetPictureUrl(int pictureId, int targetSize = 0, bool showDefaultPicture = true, string storeLocation = null, PictureType defaultPictureType = PictureType.Entity)
        {
            var picture = GetPictureById(pictureId);

            return(GetPictureUrl(picture, targetSize, showDefaultPicture, storeLocation, defaultPictureType));
        }
Beispiel #59
0
        public int AddPicture(byte[] pictureData, PictureType format)
        {
            int imageNumber = GetAllPictures().Count + 1;
            XSSFPictureData img = (XSSFPictureData)CreateRelationship(XSSFPictureData.RELATIONS[(int)format], XSSFFactory.GetInstance(), imageNumber, true);
            try
            {
                Stream out1 = img.GetPackagePart().GetOutputStream();
                out1.Write(pictureData, 0, pictureData.Length);
                out1.Close();
            }
            catch (IOException e)
            {
                throw new POIXMLException(e);
            }
            pictures.Add(img);
            return imageNumber - 1;

        }
Beispiel #60
0
        public async Task <IEnumerable <Visit> > GetUserVisits(string filter, PictureType pictureType, int pageSize, int pageCount, DateTime dateFilter)
        {
            var identity = _securityHelper.GetUser();

            return(await _visitRepository.GetUserVisitsAsync(identity, filter, pictureType, pageSize, pageCount));
        }