Пример #1
0
        public IHttpActionResult PutProduct(int id, Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != product.Id)
            {
                return(BadRequest());
            }

            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public IHttpActionResult PutUserLogin(int id, UserLogin userLogin)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != userLogin.UserLoginID)
            {
                return(BadRequest());
            }

            db.Entry(userLogin).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserLoginExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public ActionResult Create([Bind(Include = "Id,Title,Rating")] Game game)
        {
            if (ModelState.IsValid)
            {
                db.Games.Add(game);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(game));
        }
        public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Type")] Member member)
        {
            if (ModelState.IsValid)
            {
                db.Members.Add(member);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(member));
        }
Пример #5
0
        public ActionResult Edit([Bind(Include = "Id,PoolsId,path,filename,displayname,width,heigth,hsv")] Images images)
        {
            if (ModelState.IsValid)
            {
                db.Entry(images).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Details", "Pools", new { id = images.PoolsId }));
            }

            ViewBag.PoolsId = new SelectList(db.PoolsSet, "Id", "name", images.PoolsId);
            return(View(images));
        }
Пример #6
0
        public ActionResult Create([Bind(Include = "Id,City,MemberId")] Address address)
        {
            if (ModelState.IsValid)
            {
                db.Addresses.Add(address);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.MemberId = new SelectList(db.Members, "Id", "FirstName", address.MemberId);
            return(View(address));
        }
Пример #7
0
        public ActionResult Update([Bind(Include = "UserName,Password,Email, City, FirstName, LastName, State,Zipcode, Address")] User _user)
        {
            if (ModelState.IsValid)
            {
                if (UserManager.User != null)
                {
                    User user = (from u in db.Users
                                 where u.UserId == UserManager.User.Id
                                 select u
                                 ).FirstOrDefault();
                    user.UserName  = _user.UserName;
                    user.Password  = _user.Password;
                    user.Email     = _user.Email;
                    user.City      = _user.City;
                    user.FirstName = _user.FirstName;
                    user.LastName  = _user.LastName;
                    user.State     = _user.State;
                    user.ZipCode   = _user.ZipCode;
                    user.Address   = _user.Address;

                    db.SaveChanges();

                    ModelState.Clear();

                    return(RedirectToAction("Index", "Category"));
                }
                else
                {
                    db.Users.Add(_user);
                    db.SaveChanges();

                    Logon logon = new Logon();
                    logon.Username = _user.UserName;
                    logon.Password = _user.Password;
                    if (_user.UserId > 0 && UserManager.ValidateUser(logon, Response))
                    {
                        ModelState.Clear();

                        return(RedirectToAction("Index", "Category"));
                    }
                }

                ModelState.Clear();
            }

            ViewBag.RegisterFailure = 1;    // errors ocured
            return(View("Index", _user));
        }
Пример #8
0
        public string SetTransaction(string TransactionID, string SerialNumber, string ProductKeyID)
        {
            long prodcutKeyID = -9;

            if (!long.TryParse(ProductKeyID, out prodcutKeyID))
            {
                throw new FormatException("Invalid value supplied for product key ID!");
            }

            string returnValue = "";

            using (DBModelContainer context = new DBModelContainer())
            {
                ProductKeyIDSerialNumberPairs pair = context.ProductKeyIDSerialNumberPairs.FirstOrDefault((o) => ((o.SerialNumber.ToLower().StartsWith(SerialNumber.ToLower())) && (o.TransactionID.ToLower() == TransactionID.ToLower())));

                //ProductKeyIDSerialNumberPairs pair = context.ProductKeyIDSerialNumberPairs.FirstOrDefault((o) => (o.TransactionID.ToLower() == TransactionID.ToLower()));

                if (pair != null)
                {
                    pair.ProductKeyID     = prodcutKeyID;
                    pair.ModificationTime = DateTime.Now;

                    returnValue = pair.PairID.ToString();

                    context.SaveChanges();
                }
            }

            return(returnValue);
        }
Пример #9
0
        public string[] Bind(string SerialNumber, string ProductKeyID)
        {
            long prodcutKeyID = -9;

            if (!long.TryParse(ProductKeyID, out prodcutKeyID))
            {
                throw new FormatException("Invalid value supplied for product key ID!");
            }

            string[] returnValue = null;

            List <string> transactionIDs = new List <string>();

            using (DBModelContainer context = new DBModelContainer())
            {
                foreach (var pair in context.ProductKeyIDSerialNumberPairs.Where((o) => (o.SerialNumber.Trim().ToLower() == SerialNumber.ToLower())))
                {
                    if (pair != null)
                    {
                        pair.ProductKeyID     = prodcutKeyID;
                        pair.ModificationTime = DateTime.Now;

                        transactionIDs.Add(pair.TransactionID);
                    }
                }

                returnValue = transactionIDs.ToArray();

                context.SaveChanges();
            }

            return(returnValue);
        }
Пример #10
0
        public object Add(string TransactionID, string SerialNumber)
        {
            Guid pairID = Guid.NewGuid();

            using (DBModelContainer context = new DBModelContainer())
            {
                context.ProductKeyIDSerialNumberPairs.Add(new ProductKeyIDSerialNumberPairs()
                {
                    PairID        = pairID,
                    TransactionID = TransactionID,
                    SerialNumber  = SerialNumber,
                    CreationTime  = DateTime.Now,
                    SeriesID      = ((this.Parameters.ContainsKey("SeriesID")) && (this.Parameters["SeriesID"] != null)) ? this.Parameters["SeriesID"].ToString() : "",
                    SeriesName    = ((this.Parameters.ContainsKey("SeriesName")) && (this.Parameters["SeriesName"] != null)) ? this.Parameters["SeriesName"].ToString() : "",
                    ModelID       = ((this.Parameters.ContainsKey("ModelID")) && (this.Parameters["ModelID"] != null)) ? this.Parameters["ModelID"].ToString() : "",
                    ModelName     = ((this.Parameters.ContainsKey("ModelName")) && (this.Parameters["ModelName"] != null)) ? this.Parameters["ModelName"].ToString() : "",
                    DeviceID      = ((this.Parameters.ContainsKey("DeviceID")) && (this.Parameters["DeviceID"] != null)) ? this.Parameters["DeviceID"].ToString() : "",
                    DeviceName    = ((this.Parameters.ContainsKey("DeviceName")) && (this.Parameters["DeviceName"] != null)) ? this.Parameters["DeviceName"].ToString() : "",
                    OperatorID    = ((this.Parameters.ContainsKey("OperatorID")) && (this.Parameters["OperatorID"] != null)) ? this.Parameters["OperatorID"].ToString() : "",
                    OperatorName  = ((this.Parameters.ContainsKey("OperatorName")) && (this.Parameters["OperatorName"] != null)) ? this.Parameters["OperatorName"].ToString() : "",
                    StationID     = ((this.Parameters.ContainsKey("StationID")) && (this.Parameters["StationID"] != null)) ? this.Parameters["StationID"].ToString() : "",
                    StationName   = ((this.Parameters.ContainsKey("StationName")) && (this.Parameters["StationName"] != null)) ? this.Parameters["StationName"].ToString() : "",
                    LineID        = ((this.Parameters.ContainsKey("LineID")) && (this.Parameters["LineID"] != null)) ? this.Parameters["LineID"].ToString() : "",
                    LineName      = ((this.Parameters.ContainsKey("LineName")) && (this.Parameters["LineName"] != null)) ? this.Parameters["LineName"].ToString() : "",
                    BusinessID    = ((this.Parameters.ContainsKey("BusinessID")) && (this.Parameters["BusinessID"] != null)) ? this.Parameters["BusinessID"].ToString() : "",
                    BusinessName  = ((this.Parameters.ContainsKey("BusinessName")) && (this.Parameters["BusinessName"] != null)) ? this.Parameters["BusinessName"].ToString() : "",
                    OrderID       = ((this.Parameters.ContainsKey("OrderID")) && (this.Parameters["OrderID"] != null)) ? this.Parameters["OrderID"].ToString() : ""
                });

                context.SaveChanges();
            }

            return(pairID.ToString());
        }
Пример #11
0
        public ActionResult Bildersammlungen([Bind(Include = "Id,owner,name,size,writelock")] Pools pools)
        {
            if (ModelState.IsValid)
            {
                db.PoolsSet.Add(pools);
                db.SaveChanges();
            }

            return(RedirectToAction("Bildersammlungen"));
        }
Пример #12
0
        public string AddTransaction(ProductKeyIDSerialNumberPairs Transaction)
        {
            string returnValue = "";

            using (DBModelContainer context = new DBModelContainer())
            {
                Transaction.CreationTime = DateTime.Now;

                var result = context.ProductKeyIDSerialNumberPairs.Add(Transaction);

                context.SaveChanges();

                returnValue = result.TransactionID;
            }

            return(returnValue);
        }
Пример #13
0
 public int Complete()
 {
     try
     {
         return(_context.SaveChanges());
     }
     catch (DbEntityValidationException e)
     {
         foreach (var eve in e.EntityValidationErrors)
         {
             Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                               eve.Entry.Entity.GetType().Name, eve.Entry.State);
             foreach (var ve in eve.ValidationErrors)
             {
                 Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                   ve.PropertyName, ve.ErrorMessage);
             }
         }
         throw;
     }
 }
Пример #14
0
        public object Save(DataPair DataPair)
        {
            DBDataIdentifier identifier = new DBDataIdentifier()
            {
                DataUniqueID = DataPair.Identifier.DataUniqueID,
                DataType     = ((DBDataType)(DataPair.Identifier.DataType)),
                RawData      = DataPair.Identifier.RawData as byte[]
            };

            DBDataItem dataItem;

            List <DBDataItem> dataItems = new List <DBDataItem>();

            List <string> dataItemIDList = null;

            for (int i = 0; i < DataPair.Items.Count; i++)
            {
                dataItem = new DBDataItem()
                {
                    DataItemID     = Guid.NewGuid().ToString(),
                    DataIdentifier = identifier,
                    DataUniqueID   = DataPair.Identifier.DataUniqueID,
                    CreationTime   = DataPair.Items[i].CreationTime,
                    DataBytes      = DataPair.Items[i].DataBytes,
                    Description    = DataPair.Items[i].Description,
                    DeviceID       = DataPair.Items[i].DeviceID,
                    LocationID     = DataPair.Items[i].LocationID,
                    Size           = DataPair.Items[i].Size
                };

                List <DBDataParameter> dataParameters = new List <DBDataParameter>();


                if (DataPair.Items[i].DataParameters != null)
                {
                    for (int j = 0; j < DataPair.Items[i].DataParameters.Count; j++)
                    {
                        dataParameters.Add(new DBDataParameter()
                        {
                            ID         = Guid.NewGuid().ToString(),
                            Name       = DataPair.Items[i].DataParameters[j].Name,
                            Value      = DataPair.Items[i].DataParameters[j].Value,
                            DataItem   = dataItem,
                            DataItemID = dataItem.DataItemID
                        });
                    }
                }

                dataItem.DataParameters = dataParameters.ToArray();
                dataItems.Add(dataItem);
            }

            identifier.DataItems = dataItems.ToArray();

            using (DBModelContainer context = new DBModelContainer())
            {
                var dbident = context.DBDataIdentifiers.FirstOrDefault((o) => (o.DataUniqueID.ToLower() == identifier.DataUniqueID.ToLower()));

                if (dbident != null)
                {
                    foreach (var item in identifier.DataItems)
                    {
                        //dbident.DataItems.Add(item);
                        item.DataIdentifier = dbident;
                        context.DBDataItems.Add(item);
                    }

                    //identifier = dbident;
                }
                else
                {
                    identifier = context.DBDataIdentifiers.Add(identifier);
                }

                context.SaveChanges();
            }

            if (identifier != null)
            {
                dataItemIDList = new List <string>();

                foreach (var item in identifier.DataItems)
                {
                    dataItemIDList.Add(item.DataItemID);
                }
            }

            return(dataItemIDList);
        }
Пример #15
0
 public void Save()
 {
     _context.SaveChanges();
 }
Пример #16
0
        /// <summary>
        /// Erstellt eine Kachel
        /// </summary>
        /// <param name="kachelPoolID">Der Pool in dem die Kachel gespeichert werden soll</param>
        /// <param name="r">Der Rot-Anteil der Kachelfarbe</param>
        /// <param name="g">Der Grün-Anteil der Kachelfarbe</param>
        /// <param name="b">Der Blau-Anteil der Kachelfarbe</param>
        /// <param name="nois">Es kann ein Rauschen der Farbwerte erzeugt werden</param>
        /// <returns>Void</returns>
        public void genKachel(int kachelPoolID, int r, int g, int b, bool nois = false)
        {
            int nr = r;
            int ng = g;
            int nb = b;
            int boul;
            int rand;

            printToConsole("Find pool by Id: " + kachelPoolID, ConsolePrintTypes.INFO);
            Pools kachelPool = db.PoolsSet.Where(p => p.Id == kachelPoolID).First();

            printToConsole("R: " + r + "G: " + g + "B: " + b + "Nois: " + nois, ConsolePrintTypes.INFO);

            printToConsole("Kachelsize " + kachelPool.size + "x" + kachelPool.size, ConsolePrintTypes.INFO);
            int width  = kachelPool.size;
            int height = kachelPool.size;

            Random random = new Random();
            Bitmap bitmap = new Bitmap(width, height);

            try {
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        if (nois)
                        {
                            boul = random.Next(0, 1);
                            rand = random.Next(50, 70);

                            if (boul == 1)
                            {
                                nr = r + rand;
                                ng = g + rand;
                                nb = b + rand;
                            }
                            else
                            {
                                nr = r - rand;
                                ng = g - rand;
                                nb = b - rand;
                            }

                            nr = minMax(nr);
                            ng = minMax(ng);
                            nb = minMax(nb);
                        }
                        bitmap.SetPixel(x, y, Color.FromArgb(nr, ng, nb));
                    }
                }
            }
            catch (Exception e)
            {
                printToConsole(e.ToString(), ConsolePrintTypes.INFO);
            }

            // Generiere eine Einzigartige Bezeichnung
            String UUID = Guid.NewGuid().ToString();

            printToConsole("gen UUID: " + UUID, ConsolePrintTypes.INFO);

            // Speichere das Bild ab
            bitmap.Save(IMAGEPATH + "Kacheln\\" + UUID + ".png");
            printToConsole("Save image to: " + IMAGEPATH + "Kacheln\\" + UUID + ".png", ConsolePrintTypes.INFO);

            var kachel = db.Set <Kacheln>();

            kachel.Add(new Kacheln
            {
                displayname = "Kachel",
                filename    = UUID + ".png",
                path        = "Kacheln\\",
                heigth      = bitmap.Size.Height,
                width       = bitmap.Size.Width,
                hsv         = "000",
                PoolsId     = kachelPoolID,
                avgR        = (int)colorValue(bitmap, ColorType.RED),
                avgG        = (int)colorValue(bitmap, ColorType.GREEN),
                avgB        = (int)colorValue(bitmap, ColorType.BLUE)
            });

            // Speichere die DB
            db.SaveChanges();
            printToConsole("Generation done!", ConsolePrintTypes.INFO);

            bitmap.Dispose();
        }
Пример #17
0
        /// <summary>
        /// Der eigentliche Mosaikgenerator. Liest Kacheln aus und fuegt diese an die passenden Stellen fuer das Originalbild ein
        /// </summary>
        /// <param name="basisMotivID">Die ID des Basismotivs</param>
        /// <param name="kachelPoolID">Die ID des Kachelpools</param>
        /// <param name="mosaikPoolID">Die ID des Mosaikpools (in dem das Bild gespeichert wird)</param>
        /// <param name="kachelnMultiUseEnabled">Sollen Kacheln mehrfach genutzt werden duerfen?</param>
        /// <param name="auswahlNBesteKacheln">Aus wievielen der besten Bilder soll ein zufaelliges ausgewaehlt werden?</param>
        public bool mosaikGenerator(int basisMotivID, int kachelPoolID, int mosaikPoolID, Boolean kachelnMultiUseEnabled = true, int auswahlNBesteKacheln = 1)
        {
            printToConsole("MosaikStart! (" + basisMotivID + "--" + kachelPoolID + "--" + mosaikPoolID + "--" + auswahlNBesteKacheln + ")", ConsolePrintTypes.INFO);

            // Pruefe ob alle wichtigen Parameter richtig gesetzt sind
            if (basisMotivID < 1 && kachelPoolID < 1 && mosaikPoolID < 1 && auswahlNBesteKacheln < 1)
            {
                printToConsole("Falscher Parameter - Abbruch! (" + basisMotivID + "--" + kachelPoolID + "--" + mosaikPoolID + "--" + auswahlNBesteKacheln + ")", ConsolePrintTypes.ERROR);
                return(false);
            }

            // Lade das Basismotiv in eine Bitmap
            Bitmap basisMotiv = openImage(basisMotivID);

            // Wenn basisMotiv null ist dann gab es einen Fehler beim laden des Bildes
            if (basisMotiv == null)
            {
                printToConsole("Basismotiv nicht gefunden - Abbruch!", ConsolePrintTypes.ERROR);
                return(false);
            }

            // Lade die Kachel-Poolinformationen aus der Datenbank
            Pools kachelPool = db.PoolsSet.Find(kachelPoolID);

            // Berechne die Anzahl aller Pixel
            int pixel = basisMotiv.Height * basisMotiv.Width;

            // Prüfe ob genug Kacheln im Pool sind
            // Wenn Kacheln nur einmalig erlaubt sind, muss geprueft werden ob genug vorhanden sind
            if (!kachelnMultiUseEnabled)
            {
                // Wenn weniger Kacheln als Pixel vorhanden sind...
                if (db.ImagesSet.Count <Images>() < pixel)
                {
                    basisMotiv.Dispose();
                    printToConsole("Zu wenig Kacheln im Pool!", ConsolePrintTypes.ERROR);
                    return(false);
                }
            }

            // lege ein neues Bild mit der neuen Groesse an
            // Berechnung in der Dokumentation
            Bitmap mosaik = new Bitmap((basisMotiv.Size.Width * kachelPool.size), (basisMotiv.Size.Height * kachelPool.size));

            // Falls Kacheln nur einmalig genutzt werden duerfen, muessen diese vermerkt werden
            List <int> usedKacheln = new List <int>();

            // Es soll eine Liste vorhanden sein die aus den N besten Bildern ein zufaelliges auswaehlt
            Dictionary <int, double> nKacheln = new Dictionary <int, double>();

            // Hole alle Bilder aus dem Pool
            Kacheln[] poolBilder = db.ImagesSet.OfType <Kacheln>().Where(p => p.PoolsId == kachelPoolID).ToArray();

            // Lege die Variablen zur Berechnung an
            Color  pixelFarbe;
            Random rnd = new Random();
            Bitmap thisKachel;
            int    bestfit;
            int    differenzRot   = 0;
            int    differenzGruen = 0;
            int    differenzBlau  = 0;

            // gehe jeden einzelnen Pixel des Originalbildes durch
            for (int i = 1; i < basisMotiv.Size.Width + 1; i++)
            {
                for (int j = 1; j < basisMotiv.Size.Height + 1; j++)
                {
                    // Lade die Farbwerte des aktuellen Pixels
                    pixelFarbe = basisMotiv.GetPixel(i - 1, j - 1);

                    // Gehe jedes Bild im Pool durch und pruefe ob es gut dorthin passt
                    for (int k = 0; k < poolBilder.Length; k++)
                    {
                        // Wenn Kacheln Multi disabled ist & die Kachel schonmal
                        // genutzt wurde soll der folgende Teil ignoriert werden
                        if (kachelnMultiUseEnabled || (!kachelnMultiUseEnabled && !usedKacheln.Contains(poolBilder[k].Id)))
                        {
                            // Berechne die drei jeweiligen (positiven) Differenzen
                            if (poolBilder[k].avgR > pixelFarbe.R)
                            {
                                differenzRot = poolBilder[k].avgR - pixelFarbe.R;
                            }
                            else
                            {
                                differenzRot = pixelFarbe.R - poolBilder[k].avgR;
                            }

                            if (poolBilder[k].avgG > pixelFarbe.G)
                            {
                                differenzGruen = poolBilder[k].avgG - pixelFarbe.G;
                            }
                            else
                            {
                                differenzGruen = pixelFarbe.G - poolBilder[k].avgG;
                            }

                            if (poolBilder[k].avgB > pixelFarbe.B)
                            {
                                differenzBlau = poolBilder[k].avgB - pixelFarbe.B;
                            }
                            else
                            {
                                differenzBlau = pixelFarbe.B - poolBilder[k].avgB;
                            }

                            // Rechne den Farbabstand aus (Formel aus den Hinweisen zur Hausarbeit)
                            double farbAbstand = Math.Sqrt((double)(differenzRot * differenzRot) + (differenzGruen * differenzGruen) + (differenzBlau * differenzBlau));

                            // Wenn noch Platz in dem N-Kachel-Array ist, lege den Wert ab
                            if (auswahlNBesteKacheln > nKacheln.Count)
                            {
                                nKacheln.Add(poolBilder[k].Id, farbAbstand);
                            }
                            else
                            {
                                // Ermittle den schlechtesten Wert in den N-Kacheln
                                double schlechtesterWert = 0;
                                int    index             = -1;

                                // Gehe alle Elemente durch und finde den schlechtesten Wert
                                // Dieser muss GRÖSSER als die anderen sein, da der ABSTAND möglichst niedrig sein soll
                                foreach (var nKachel in nKacheln)
                                {
                                    if (nKachel.Value > schlechtesterWert)
                                    {
                                        index             = nKachel.Key;
                                        schlechtesterWert = nKachel.Value;
                                    }
                                }

                                // Wenn das ergebnis besser ist als der schlechteste Wert
                                if (farbAbstand < schlechtesterWert)
                                {
                                    // Entferne das schlechteste Element
                                    nKacheln.Remove(index);

                                    // Fuege die neue nKachel hinzu
                                    nKacheln.Add(poolBilder[k].Id, farbAbstand);
                                }
                            }
                        }
                    }

                    // Hier wurden alle Bilder im Pool für einen Pixel durchsucht
                    // Hole nur die Keys aus der Liste
                    List <int> keys = Enumerable.ToList(nKacheln.Keys);

                    // Waehle ein zufaelligen Key - und damit auch das einzusetzende Bild
                    bestfit = keys[rnd.Next(nKacheln.Count)];

                    // Bereinige die NKacheln damit sie beim nächsten durchlauf nicht nochmal vorkommen :D
                    nKacheln.Clear();

                    // Wenn Kacheln nur einmal genutzt werden sollen, muss diese Kachel gespeichert werden
                    if (!kachelnMultiUseEnabled)
                    {
                        usedKacheln.Add(bestfit);
                    }

                    // Lade die Kachel
                    thisKachel = openImage(bestfit);

                    // Wenn basisMotiv null ist dann gab es einen Fehler beim laden des Bildes
                    if (thisKachel == null)
                    {
                        printToConsole("Kachel (" + bestfit + ") nicht gefunden - Abbruch!", ConsolePrintTypes.ERROR);
                        return(false);
                    }

                    // Füge nun jeden einzelnen Pixel an seiner dafür vorgesehnen Position ein
                    for (int x = 0; x < kachelPool.size; x++)
                    {
                        for (int y = 0; y < kachelPool.size; y++)
                        {
                            // Lade die Farbwerte des aktuellen Pixels
                            pixelFarbe = thisKachel.GetPixel(x, y);

                            // Und Fuege in an die richtige Position im neuen Mosaikbild ein
                            mosaik.SetPixel((((i - 1) * kachelPool.size) + x), (((j - 1) * kachelPool.size) + y), pixelFarbe);
                        }
                    }
                }
            }

            // Generiere eine Einzigartige Bezeichnung
            String UUID = Guid.NewGuid().ToString();

            // Speichere das Bild ab
            mosaik.Save(IMAGEPATH + "Motive\\" + UUID + ".png");

            var image = db.Set <Motive>();

            image.Add(new Motive {
                displayname = "Mosaik", filename = UUID + ".png", path = "Motive\\", heigth = (basisMotiv.Size.Height * kachelPool.size), width = (basisMotiv.Size.Width * kachelPool.size), hsv = "000", PoolsId = mosaikPoolID, writelock = false
            });

            // Speichere die DB
            db.SaveChanges();

            return(true);
        }
Пример #18
0
        /// <summary>
        /// Methode schneidet einen Teil aus einem Basismotiv aus
        /// </summary>
        /// <param name="imageId">ID des Bildes in der Datenbank</param>
        /// <param name="width">Breite des Ausschnittes</param>
        /// <param name="height">Höhe des Ausschnittes</param>
        /// <param name="mode">Gibt an wo der Bildausschnitt starten soll</param>
        /// <returns>Erfolg oder misserfolg</returns>
        public bool crop(int imageId, int width, int height, CropModiTypes mode)
        {
            printToConsole("Start cropping ...", ConsolePrintTypes.INFO);

            printToConsole("Cropping to " + width + "x" + height, ConsolePrintTypes.INFO);

            try
            {
                String imagePath     = db.ImagesSet.Where(p => p.Id == imageId).First().path;
                String imageFileName = db.ImagesSet.Where(p => p.Id == imageId).First().filename;

                // Crop image on filesystem
                Bitmap originalBitmap = openImage(imageId);
                if (originalBitmap == null)
                {
                    printToConsole("Cropping faild!", ConsolePrintTypes.WARNING);
                    return(false);
                }

                Bitmap newBitmap = new Bitmap(originalBitmap.Width, originalBitmap.Height);

                int deltaWidth  = originalBitmap.Width - width;
                int deltaHeight = originalBitmap.Height - height;
                int cropLeft    = deltaWidth / 2;
                int cropTop     = deltaHeight / 2;

                printToConsole("Cropmode: " + mode, ConsolePrintTypes.INFO);

                switch (mode)
                {
                case CropModiTypes.MIDDLE:
                    newBitmap = originalBitmap.Clone(new Rectangle(cropLeft, cropTop, width, height), originalBitmap.PixelFormat);
                    break;

                case CropModiTypes.CENTERLEFT:
                    newBitmap = originalBitmap.Clone(new Rectangle(0, cropTop, width, height), originalBitmap.PixelFormat);
                    break;

                case CropModiTypes.CENTERRIGHT:
                    newBitmap = originalBitmap.Clone(new Rectangle(deltaWidth, cropTop, width, height), originalBitmap.PixelFormat);
                    break;

                case CropModiTypes.TOPLEFT:
                    newBitmap = originalBitmap.Clone(new Rectangle(0, 0, width, height), originalBitmap.PixelFormat);
                    break;

                case CropModiTypes.TOPRIGHT:
                    newBitmap = originalBitmap.Clone(new Rectangle(width, 0, width, height), originalBitmap.PixelFormat);
                    break;

                case CropModiTypes.BOTTOMLEFT:
                    newBitmap = originalBitmap.Clone(new Rectangle(0, height, width, height), originalBitmap.PixelFormat);
                    break;

                case CropModiTypes.BOTTOMRIGHT:
                    newBitmap = originalBitmap.Clone(new Rectangle(width, height, width, height), originalBitmap.PixelFormat);
                    break;
                }

                originalBitmap.Dispose();
                printToConsole("Save file to: " + IMAGEPATH + imagePath + imageFileName, ConsolePrintTypes.INFO);
                newBitmap.Save(IMAGEPATH + imagePath + imageFileName);

                double red   = 0;
                double green = 0;
                double blue  = 0;
                var    ges   = newBitmap.Width * newBitmap.Height;
                for (int i = 0; i < newBitmap.Width; i++)
                {
                    for (int j = 0; j < newBitmap.Height; j++)
                    {
                        Color rgb = newBitmap.GetPixel(i, j);
                        red   += rgb.R;
                        green += rgb.G;
                        blue  += rgb.B;
                    }
                }
                red   = red / ges;
                green = green / ges;
                blue  = blue / ges;

                // Set new values in database
                Kacheln img = db.ImagesSet.OfType <Kacheln>().Where(p => p.Id == imageId).First();
                printToConsole("Set image width to: " + newBitmap.Width, ConsolePrintTypes.INFO);
                img.width = newBitmap.Width;
                printToConsole("Set image heigth to: " + newBitmap.Height, ConsolePrintTypes.INFO);
                img.heigth = newBitmap.Height;
                printToConsole("Set image avgR to: " + (int)red, ConsolePrintTypes.INFO);
                img.avgR = (int)red;
                printToConsole("Set image avgG to: " + (int)green, ConsolePrintTypes.INFO);
                img.avgG = (int)green;
                printToConsole("Set image avgB to: " + (int)blue, ConsolePrintTypes.INFO);
                img.avgB = (int)blue;
                db.SaveChanges();

                newBitmap.Dispose();

                printToConsole("Image: " + img.path + img.filename + " croped successfully.", ConsolePrintTypes.INFO);
                return(true);
            }
            catch (Exception e)
            {
                printToConsole(e.ToString(), ConsolePrintTypes.WARNING);
                printToConsole("Cropping faild!", ConsolePrintTypes.WARNING);
                return(false);
            }
        }