Exemplo n.º 1
0
        static string ExifValueToString(IExifValue v)
        {
            if (v.Tag == ExifTag.UserComment || v.Tag == ExifTag.ExifVersion)
            {
                var    data = v.GetValue() as byte[];
                string s    = Encoding.UTF8.GetString(data);
                return(s);
            }

            if (v.IsArray)
            {
                if (v.DataType == ExifDataType.Undefined || v.DataType == ExifDataType.Byte)
                {
                    var    data    = v.GetValue() as byte[];
                    int    max     = Math.Min(data.Length, MaxBytesToShow);
                    string hasMore = data.Length > MaxBytesToShow ? " ..." : "";
                    string hex     = BitConverter.ToString(data, 0, max).Replace("-", " ");
                    string s       = $"Bytes [{hex}{hasMore}]";
                    return(s);
                }

                return($"[not implemented. type:{v.DataType}]");
            }
            else
            {
                return(v.GetValue().ToString());
            }
        }
Exemplo n.º 2
0
        private int WriteArray(IExifValue value, Span <byte> destination, int offset)
        {
            if (value.DataType == ExifDataType.Ascii)
            {
                return(this.WriteValue(ExifDataType.Ascii, value.GetValue(), destination, offset));
            }

            int newOffset = offset;

            foreach (object obj in (Array)value.GetValue())
            {
                newOffset = this.WriteValue(value.DataType, obj, destination, newOffset);
            }

            return(newOffset);
        }
Exemplo n.º 3
0
        internal static uint GetNumberOfComponents(IExifValue exifValue)
        {
            object value = exifValue.GetValue();

            if (ExifUcs2StringHelpers.IsUcs2Tag((ExifTagValue)(ushort)exifValue.Tag))
            {
                return((uint)ExifUcs2StringHelpers.Ucs2Encoding.GetByteCount((string)value));
            }

            if (value is EncodedString encodedString)
            {
                return(ExifEncodedStringHelpers.GetDataLength(encodedString));
            }

            if (exifValue.DataType == ExifDataType.Ascii)
            {
                return((uint)ExifConstants.DefaultEncoding.GetByteCount((string)value) + 1);
            }

            if (value is Array arrayValue)
            {
                return((uint)arrayValue.Length);
            }

            return(1);
        }
Exemplo n.º 4
0
        protected override JProperty Transform(IExifValue value)
        {
            Byte[]   bytes   = (Byte[])value.GetValue();
            string[] strings = bytes.Select(b => b.ToString()).ToArray();
            string   version = string.Join('.', strings);

            return(new JProperty(Name, version));
        }
Exemplo n.º 5
0
        private static int WriteArray(IExifValue value, Span <byte> destination, int offset)
        {
            int newOffset = offset;

            foreach (object obj in (Array)value.GetValue())
            {
                newOffset = WriteValue(value.DataType, obj, destination, newOffset);
            }

            return(newOffset);
        }
Exemplo n.º 6
0
        private static uint GetNumberOfComponents(IExifValue exifValue)
        {
            object value = exifValue.GetValue();

            if (exifValue.DataType == ExifDataType.Ascii)
            {
                return((uint)Encoding.UTF8.GetBytes((string)value).Length + 1);
            }

            if (value is Array arrayValue)
            {
                return((uint)arrayValue.Length);
            }

            return(1);
        }
Exemplo n.º 7
0
        private CameraData?GetCameraData(ExifProfile exifProfile)
        {
            IExifValue <string> model = exifProfile.GetValue(ExifTag.Model);
            IExifValue <string> make  = exifProfile.GetValue(ExifTag.Make);

            if (model?.GetValue() != null)
            {
                return(new CameraData
                {
                    Model = model.ToString(),
                    Make = make.ToString()
                });
            }

            return(null);
        }
Exemplo n.º 8
0
        public void WritingImagePreservesExifProfile(TestImageWriteFormat imageFormat)
        {
            // Arrange
            var image = new Image <Rgba32>(1, 1);

            image.Metadata.ExifProfile = CreateExifProfile();

            // Act
            Image <Rgba32> reloadedImage = WriteAndRead(image, imageFormat);

            // Assert
            ExifProfile actual = reloadedImage.Metadata.ExifProfile;

            Assert.NotNull(actual);
            foreach (KeyValuePair <ExifTag, object> expectedProfileValue in TestProfileValues)
            {
                IExifValue actualProfileValue = actual.GetValueInternal(expectedProfileValue.Key);
                Assert.NotNull(actualProfileValue);
                Assert.Equal(expectedProfileValue.Value, actualProfileValue.GetValue());
            }
        }
Exemplo n.º 9
0
        private static bool HasValue(IExifValue exifValue)
        {
            object value = exifValue.GetValue();

            if (value is null)
            {
                return(false);
            }

            if (exifValue.DataType == ExifDataType.Ascii)
            {
                string stringValue = (string)value;
                return(stringValue.Length > 0);
            }

            if (value is Array arrayValue)
            {
                return(arrayValue.Length > 0);
            }

            return(true);
        }
Exemplo n.º 10
0
        public void ProfileToByteArray()
        {
            // Arrange
            byte[]      exifBytesWithoutExifCode = ExifConstants.LittleEndianByteOrderMarker;
            ExifProfile expectedProfile          = CreateExifProfile();
            var         expectedProfileTags      = expectedProfile.Values.Select(x => x.Tag).ToList();

            // Act
            byte[] actualBytes   = expectedProfile.ToByteArray();
            var    actualProfile = new ExifProfile(actualBytes);

            // Assert
            Assert.NotNull(actualBytes);
            Assert.NotEmpty(actualBytes);
            Assert.Equal(exifBytesWithoutExifCode, actualBytes.Take(exifBytesWithoutExifCode.Length).ToArray());
            foreach (ExifTag expectedProfileTag in expectedProfileTags)
            {
                IExifValue actualProfileValue   = actualProfile.GetValueInternal(expectedProfileTag);
                IExifValue expectedProfileValue = expectedProfile.GetValueInternal(expectedProfileTag);
                Assert.Equal(expectedProfileValue.GetValue(), actualProfileValue.GetValue());
            }
        }
Exemplo n.º 11
0
        public void ReadWriteLargeProfileJpg()
        {
            ExifTag <string>[] tags = new[] { ExifTag.Software, ExifTag.Copyright, ExifTag.Model, ExifTag.ImageDescription };
            foreach (ExifTag <string> tag in tags)
            {
                // Arrange
                var junk = new StringBuilder();
                for (int i = 0; i < 65600; i++)
                {
                    junk.Append("a");
                }

                var         image               = new Image <Rgba32>(100, 100);
                ExifProfile expectedProfile     = CreateExifProfile();
                var         expectedProfileTags = expectedProfile.Values.Select(x => x.Tag).ToList();
                expectedProfile.SetValue(tag, junk.ToString());
                image.Metadata.ExifProfile = expectedProfile;

                // Act
                Image <Rgba32> reloadedImage = WriteAndRead(image, TestImageWriteFormat.Jpeg);

                // Assert
                ExifProfile actualProfile = reloadedImage.Metadata.ExifProfile;
                Assert.NotNull(actualProfile);

                foreach (ExifTag expectedProfileTag in expectedProfileTags)
                {
                    IExifValue actualProfileValue   = actualProfile.GetValueInternal(expectedProfileTag);
                    IExifValue expectedProfileValue = expectedProfile.GetValueInternal(expectedProfileTag);
                    Assert.Equal(expectedProfileValue.GetValue(), actualProfileValue.GetValue());
                }

                IExifValue <string> expected = expectedProfile.GetValue(tag);
                IExifValue <string> actual   = actualProfile.GetValue(tag);
                Assert.Equal(expected, actual);
            }
        }
Exemplo n.º 12
0
 private static void TestValue(IExifValue value, string expected)
 {
     Assert.NotNull(value);
     Assert.Equal(expected, value.GetValue());
 }
Exemplo n.º 13
0
        private static TResult ParseCoordinate <TResult>(IExifValue location, IExifValue reference,
                                                         Func <double, TResult> onParsed,
                                                         Func <TResult> onFailedToParse)
        {
            if (location.DataType != ExifDataType.Rational)
            {
                return(onFailedToParse());
            }

            var value = (SixLabors.ImageSharp.Rational[])location.GetValue();

            if (!value.Any())
            {
                return(onFailedToParse());
            }

            var deg = ToDouble(value[0]);
            var min = ToDouble(value[1]) / ((double)60);
            var sec = ToDouble(value[2]) / ((double)3600);

            var locationNoRef = deg + min + sec;

            if (reference.DataType != ExifDataType.Ascii)
            {
                return(onFailedToParse());
            }

            var valueRef = (string)reference.GetValue();
            var directionalMultiplier = IsWestOrSouth() ?
                                        -1.0
                :
                                        1.0;

            var locationWithRef = locationNoRef * directionalMultiplier;

            return(onParsed(locationWithRef));

            double ToDouble(SixLabors.ImageSharp.Rational n)
            {
                var num = (double)n.Numerator;
                var den = (double)n.Denominator;

                return(num / den);
            }

            bool IsWestOrSouth()
            {
                if (valueRef.Contains('w', StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
                if (valueRef.Contains('s', StringComparison.OrdinalIgnoreCase))
                {
                    if (!valueRef.Contains('e', StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }

                return(false);
            }
        }
Exemplo n.º 14
0
 protected override JProperty Transform(IExifValue value)
 {
     ushort[] values = (ushort[])value.GetValue();
     return(new JProperty(Name, new JArray(values)));
 }
Exemplo n.º 15
0
 protected override JProperty Transform(IExifValue value)
 {
     Rational[] rationals = (Rational[])value.GetValue();
     string[]   unique    = rationals.Distinct().Select(r => r.ToString()).ToArray();
     return(new JProperty(Name, new JArray(unique)));
 }
Exemplo n.º 16
0
        public async Task <IActionResult> UploadPhotos(ICollection <IFormFile> files)
        {
            if (Request.Form.Files.Count <= 0)
            {
                return(BadRequest("No Files"));
            }

            var userId = ControllerUtility.GetUserID(this._httpContextAccessor);

            if (userId == null)
            {
                return(StatusCode(401));
            }

            // Only care about the first file
            var file = Request.Form.Files[0];

            var fileSize  = file.Length;
            var filename1 = file.FileName;
            var idx1      = filename1.LastIndexOf('.');
            var fileext   = filename1.Substring(idx1);

            var filerst = new PhotoFileSuccess();

            // Copy file to uploads folder
            filerst.deleteType = "DELETE";
            var randomFileName = Guid.NewGuid().ToString("N");

            filerst.name = randomFileName;
            var targetfilename = randomFileName + fileext;

            filerst.size = (int)fileSize;
            // To avoid mass change the existing records in db, the URL won't return.
            // filerst.url = "PhotoFile/" + targetfilename;
            // filerst.thumbnailUrl = "PhotoFile/" + randomFileName + ".thumb" + fileext;
            filerst.url          = targetfilename;
            filerst.thumbnailUrl = randomFileName + ".thumb" + fileext;
            filerst.deleteUrl    = filerst.url;

            PhotoFileErrorResult   errrst  = null;
            PhotoFileSuccessResult succrst = new PhotoFileSuccessResult();

            try
            {
                var filePath    = Path.Combine(Startup.UploadFolder, targetfilename);
                var thmFilePath = Path.Combine(Startup.UploadFolder, randomFileName + ".thumb" + fileext);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);

                    using (IMagickImage image = new MagickImage(filePath))
                    {
                        filerst.width  = image.Width;
                        filerst.height = image.Height;

                        // Add the photo
                        var pht = new Photo();
                        pht.PhotoId = randomFileName;
                        pht.Title   = pht.PhotoId;
                        pht.Desp    = pht.PhotoId;
                        pht.FileUrl = filerst.url;
                        var exifprofile = image.GetExifProfile();
                        if (exifprofile != null)
                        {
                            // AV Number
                            IExifValue value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.ApertureValue);
                            try
                            {
                                if (value != null)
                                {
                                    pht.AVNumber = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Camera Maker
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.Make);
                            try
                            {
                                if (value != null)
                                {
                                    pht.CameraMaker = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Camera Model
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.Model);
                            try
                            {
                                if (value != null)
                                {
                                    pht.CameraModel = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // ISO number
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.ISOSpeed);
                            try
                            {
                                if (value != null)
                                {
                                    pht.ISONumber = (int)value.GetValue();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Lens Model
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.LensModel);
                            try
                            {
                                if (value != null)
                                {
                                    pht.LensModel = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Shutter Speed
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.ShutterSpeedValue);
                            try
                            {
                                if (value != null)
                                {
                                    pht.ShutterSpeed = (string)value.GetValue();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                        }

                        var bThumbnailCreated = false;

                        // Retrieve the exif information
                        ExifProfile profile = (ExifProfile)image.GetExifProfile();
                        if (profile != null)
                        {
                            using (IMagickImage thumbnail = profile.CreateThumbnail())
                            {
                                // Check if exif profile contains thumbnail and save it
                                if (thumbnail != null)
                                {
                                    thumbnail.Write(thmFilePath);
                                    bThumbnailCreated = true;

                                    filerst.thumbwidth  = thumbnail.Width;
                                    filerst.thumbheight = thumbnail.Height;

                                    pht.ThumbnailFileUrl = filerst.thumbnailUrl;
                                    pht.ThumbHeight      = filerst.thumbheight;
                                    pht.ThumbWidth       = filerst.thumbwidth;
                                    pht.IsOrgThumbnail   = true;
                                }
                            }
                        }

                        if (!bThumbnailCreated)
                        {
                            MagickGeometry size = new MagickGeometry(256, 256);
                            // This will resize the image to a fixed size without maintaining the aspect ratio.
                            // Normally an image will be resized to fit inside the specified size.
                            size.IgnoreAspectRatio = false;

                            image.Resize(size);
                            filerst.thumbwidth  = image.Width;
                            filerst.thumbheight = image.Height;

                            pht.ThumbnailFileUrl = filerst.thumbnailUrl;
                            pht.ThumbHeight      = filerst.thumbheight;
                            pht.ThumbWidth       = filerst.thumbwidth;
                            pht.IsOrgThumbnail   = false;

                            // Save the result
                            image.Write(thmFilePath);
                        }

                        pht.UploadedBy   = userId;
                        pht.UploadedTime = DateTime.Now;
                        this._context.Photos.Add(pht);

                        _context.SaveChanges();
                    }
                }

                succrst.files = new List <PhotoFileSuccess>();
                succrst.files.Append(filerst);
            }
            catch (Exception exp)
            {
                errrst = new PhotoFileErrorResult();
                var fileerr = new PhotoFileError();
                fileerr.error = exp.Message;
                fileerr.name  = filename1;
                errrst.files  = new List <PhotoFileError>();
                errrst.files.Append(fileerr);
            }

            if (errrst != null)
            {
                return(new JsonResult(errrst));
            }
            return(new JsonResult(filerst));
        }