public IActionResult UploadImage(IFormCollection data) { var id = data["id"]; Product p = _context.Product.Find(id); ProductImage pi = _context.ProductImage.Where(i => i.product_id == p.Id).OrderByDescending(i => i.position).FirstOrDefault(); int position = 0; if (pi != null) { position = pi.position + 1; } else { position = 1; } string filename = $"{p.SEOTitle.ToUpper().Replace("| ", "").Replace(" ", "_")}_{position}.jpg"; string file = data["imageFile"].ToString(); file = file.Substring(file.IndexOf(',') + 1); dynamic JProduct = new { image = new { attachment = file, filename = filename, alt = filename, } }; IRestResponse response = CallShopify($"products/{id}/images.json", Method.POST, JProduct); if (response.StatusCode.ToString().Equals("OK")) { MasterImage mi = JsonConvert.DeserializeObject <MasterImage>(response.Content); ProductImage pis = new ProductImage(); pis.id = mi.image.id; pis.product_id = p.Id; pis.position = mi.image.position; pis.src = mi.image.src; pis.alt = mi.image.alt; _context.ProductImage.Add(pis); _context.SaveChanges(); return(Ok(mi.image.id)); } else { _logger.LogError("Error updating product image: " + response.ErrorMessage); return(NotFound(response.ErrorMessage)); } }
private void WriteXmpMetaData(string imageFilePath, MasterImage masterImage, bool alwaysWriteMetadata, bool preview) { bool writeMetadata = false; IXmpMeta xmp = XmpMetaFactory.Create(); if ((!String.IsNullOrEmpty(masterImage.Caption) && !IsEquivalent(masterImage.Caption, imageFilePath)) || alwaysWriteMetadata) { xmp.AppendArrayItem(XmpConstants.NsDC, "dc:title", new PropertyOptions { IsArrayAlternate = true }, masterImage.Caption, null); writeMetadata = true; } if (!String.IsNullOrEmpty(masterImage.Comment)) { xmp.AppendArrayItem(XmpConstants.NsDC, "dc:description", new PropertyOptions { IsArrayAlternate = true }, masterImage.Comment, null); writeMetadata = true; } if (masterImage.Rating != null && (int)masterImage.Rating > 0) { xmp.SetProperty(XmpConstants.NsXmp, "xmp:Rating", ((int)masterImage.Rating).ToString()); writeMetadata = true; } // TODO: Handle faces. if (writeMetadata) { string metaFilePath = Path.ChangeExtension(imageFilePath, ".xmp"); if (File.Exists(metaFilePath)) { Console.Error.WriteLine("ERROR: XMP meta file already exists, skipping '" + metaFilePath + "'."); } else if (!preview) { Directory.CreateDirectory(Path.GetDirectoryName(metaFilePath)); using (var stream = File.OpenWrite(metaFilePath)) { XmpMetaFactory.Serialize(xmp, stream, new SerializeOptions { OmitPacketWrapper = true }); } numMetadataFilesCreated++; } } }
/// <summary> /// Compares the images into the given result. /// </summary> private unsafe void CompareData(ComparisonResult result) { sampleData = null; masterData = BitmapUtils.LockBitmapDataRead(MasterImage); try { sampleData = BitmapUtils.LockBitmapDataRead(SampleImage); int width = MasterScanLineWidth; positions = PositionDelta.ForWithinDistance(Criteria.MaxPixelDistance); maxSquareDistance = (255 * 255 + 255 * 255 + 255 * 255) * Criteria.MaxColorDistance; minSquareDistance = (255 * 255 + 255 * 255 + 255 * 255) * Criteria.MinColorDistance; int errorCount = 0; for (int y = 0; y < MasterSize.Height; y++) { PixelData *masterPixels = (PixelData *) ((byte *)masterData.Scan0.ToPointer() + y * width); PixelData *samplePixels = (PixelData *) ((byte *)sampleData.Scan0.ToPointer() + y * width); for (int x = 0; x < MasterSize.Width; x++) { bool match = PixelsEqual(*masterPixels, *samplePixels); if (!match || minSquareDistance != 0) { result.SetIdentical(false); CheckPixel(x, y, result, ref errorCount); if (errorCount > MaxErrorCount) { result.SetCriteriaMet(false); return; } } masterPixels++; samplePixels++; } } } finally { MasterImage.UnlockBits(masterData); if (sampleData != null) { SampleImage.UnlockBits(sampleData); } masterData = null; sampleData = null; } }
private unsafe void CompareData(ComparisonResult result) { BitmapData sampleData = null; BitmapData masterData = MasterImage.LockBits(MasterRectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { sampleData = SampleImage.LockBits(SampleRectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); int width = MasterScanLineWidth; int errorCount = 0; PixelData *masterPixels; PixelData *samplePixels = (PixelData *)sampleData.Scan0; for (int y = 0; y < MasterSize.Height; y++) { masterPixels = (PixelData *) ((byte *)masterData.Scan0.ToPointer() + y * width); samplePixels = (PixelData *) ((byte *)sampleData.Scan0.ToPointer() + y * width); for (int x = 0; x < MasterSize.Width; x++) { bool match = PixelsEqual(*masterPixels, *samplePixels); if (!match) { result.AddDifference( new PixelColorDifference(x, y, masterPixels->red, masterPixels->green, masterPixels->blue, samplePixels->red, samplePixels->green, samplePixels->blue)); result.SetIdentical(false); errorCount++; if (errorCount > MaxErrorCount) { result.SetCriteriaMet(false); return; } } masterPixels++; samplePixels++; } } } finally { MasterImage.UnlockBits(masterData); if (sampleData != null) { SampleImage.UnlockBits(sampleData); } } }
string GetUniqueFileNameForImage(string destRollPath, MasterImage masterImage) { string extension = Path.GetExtension(masterImage.ImagePath); string imageFileName = Path.GetFileNameWithoutExtension(masterImage.ImagePath); string desiredName = imageFileName; if (!String.IsNullOrWhiteSpace(masterImage.Caption) && !IsEquivalent(masterImage.Caption, masterImage.ImagePath) && !HasMatchingExtension(masterImage.Caption, masterImage.ImagePath)) { desiredName = masterImage.Caption.Trim(); int maxNameLen = Math.Max(80, imageFileName.Length); if (desiredName.Length > maxNameLen) { desiredName = desiredName.Substring(0, maxNameLen); } } desiredName = CleanFileOrDirectoryName(desiredName); // Make name unique. HashSet <string> usedNames; if (!uniqueFilenameTracking.TryGetValue(destRollPath.ToLower(), out usedNames)) { usedNames = new HashSet <string>(); uniqueFilenameTracking[destRollPath.ToLower()] = usedNames; } string name = desiredName; for (int i = 1; usedNames.Contains((name + extension).ToLower()); i++) { name = desiredName + " (" + i.ToString() + ")"; } usedNames.Add((name + extension).ToLower()); if (name != imageFileName) { // Console.WriteLine("Modifed image name from '" + Path.Combine(destRollPath, imageFileName + extension) + "' to '" + Path.Combine(destRollPath, name + extension) + "'."); } return(name + extension); }
/// <summary> /// Calculates sizes and other metrics for the given images. Stores /// relevant metrics in the result. /// </summary> /// <param name="result">Comparison result to set metrics on.</param> protected void CalculateMetrics(ComparisonResult result) { // Calculate sizes. GraphicsUnit unit = GraphicsUnit.Pixel; RectangleF masterRect = MasterImage.GetBounds(ref unit); this.masterSize = new Size((int)masterRect.Width, (int)masterRect.Height); RectangleF sampleRect = SampleImage.GetBounds(ref unit); this.sampleSize = new Size((int)sampleRect.Width, (int)sampleRect.Height); this.masterRectangle = new Rectangle(0, 0, MasterSize.Width, MasterSize.Height); this.sampleRectangle = new Rectangle(0, 0, SampleSize.Width, SampleSize.Height); this.maxErrorCount = (int) (MasterPixelCount * Criteria.MaxErrorProportion); // Add relevant metrics to comparison result. result.SetMasterImagePixelCount(MasterPixelCount); result.SetErrorProportion(Criteria.MaxErrorProportion); }
public void Run(string[] args) { bool unflaggedToExtras; bool copyOriginals; bool writeMetadataFiles; bool alwaysWriteMetadata; bool prependDateToEventNames; bool generateSynoCovers; if (!GetOptions(ref args, out unflaggedToExtras, out copyOriginals, out writeMetadataFiles, out alwaysWriteMetadata, out prependDateToEventNames, out generateSynoCovers)) { PrintUsage(); return; } if (args.Length != 3) { PrintUsage(); return; } string mode = args[0]; string iPhotoLibraryPath = args[1]; string outputFolderPath = args[2]; if (mode != "preview" && mode != "copy") { Console.Error.WriteLine("Invalid mode '" + mode + "'."); PrintUsage(); return; } if (!Directory.Exists(iPhotoLibraryPath)) { Console.Error.WriteLine("Can't find iphoto library folder '" + iPhotoLibraryPath + "'."); PrintUsage(); return; } if (!Directory.Exists(outputFolderPath)) { Console.Error.WriteLine("Can't find output folder'" + outputFolderPath + "'."); PrintUsage(); return; } string iPhotoXmlPath = Path.Combine(iPhotoLibraryPath, "AlbumData.xml"); if (!File.Exists(iPhotoXmlPath)) { Console.Error.WriteLine("Can't find iphoto ablum data XML '" + iPhotoXmlPath + "'."); PrintUsage(); return; } bool preview = mode == "preview"; albumData = AlbumData.Load(iPhotoXmlPath); RemoveUnreferencedRolls(); if (prependDateToEventNames) { PrependDateToEventNames(); } MakeRollNamesUnique(); List <MasterImage> masterImages = albumData.MasterImages.Values.ToList(); for (int imageIndex = 0; imageIndex < masterImages.Count; imageIndex++) { if (imageIndex % 500 == 0) { Console.WriteLine(String.Format("Copying {0:0.0}% complete ({1:n0} of {2:n0})", imageIndex / (float)masterImages.Count * 100, imageIndex, masterImages.Count)); } MasterImage masterImage = masterImages[imageIndex]; Roll roll = albumData.Rolls[(int)masterImage.Roll]; string destRollPath = roll.RollName; if (unflaggedToExtras && !masterImage.Flagged) { destRollPath = Path.Combine(destRollPath, "Extras"); } string destFileName = GetUniqueFileNameForImage(destRollPath, masterImage); string destFilePath = Path.Combine(outputFolderPath, destRollPath, destFileName); if (CopyFile(iPhotoLibraryPath, masterImage.ImagePath, destFilePath, preview)) { if (writeMetadataFiles || alwaysWriteMetadata) { WriteXmpMetaData(destFilePath, masterImage, alwaysWriteMetadata, preview); } if (copyOriginals && masterImage.OriginalPath != null && masterImage.OriginalPath != masterImage.ImagePath) { string originalDestFilePath = Path.Combine(Path.GetDirectoryName(destFilePath), "Originals", Path.GetFileNameWithoutExtension(destFilePath) + Path.GetExtension(masterImage.OriginalPath)); CopyFile(iPhotoLibraryPath, masterImage.OriginalPath, originalDestFilePath, preview); } } } if (generateSynoCovers) { // Caution using this, it is not complete/robust. Console.WriteLine("Generating covers for Synology Photo Station."); foreach (Roll roll in albumData.Rolls.Values) { GenerateSynoCover(roll, outputFolderPath, preview); } } Console.WriteLine(String.Format("Done. {0} files copied, {1} metadata files written.", numFilesCopied, numMetadataFilesCreated)); }