2017-02-22 3 views
0

Он отображает текст в изображении, но не сохраняет его в базе данных. Предыдущее изображение без текста сохраняется в db.Сохранить изображение в базе данных с текстом в C#

Помогите сохранить текст также в Изображ. В db.

public void ImageText() 
{ 
      Image bitmap = Image.FromFile(Server.MapPath("~/Image/IMG_20160930_082316.jpg")); 
      //draw the image object using a Graphics object 
      Graphics graphicsImage = Graphics.FromImage(bitmap); 
      //Set the alignment based on the coordinates 
      StringFormat stringformat = new StringFormat(); 
      stringformat.Alignment = StringAlignment.Far; 
      stringformat.LineAlignment = StringAlignment.Far; 
      StringFormat stringformat2 = new StringFormat(); 
      stringformat2.Alignment = StringAlignment.Center; 
      stringformat2.LineAlignment = StringAlignment.Center; 
      //Set the font color/format/size etc.. 
      Color StringColor = System.Drawing.ColorTranslator.FromHtml("#933eea");//direct color adding 
      Color StringColor2 = System.Drawing.ColorTranslator.FromHtml("#e80c88");//customise color adding 
      string Str_TextOnImage = "Hello";//Your Text On Image 
      string Str_TextOnImage2 = "Word";//Your Text On Image 
      graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 40, 
      FontStyle.Regular), new SolidBrush(StringColor), new Point(268, 245), 
      stringformat); Response.ContentType = "image/jpeg"; 
      graphicsImage.DrawString(Str_TextOnImage2, new Font("Edwardian Script ITC", 111, 
      FontStyle.Bold), new SolidBrush(StringColor2), new Point(145, 255), 
      stringformat2); Response.ContentType = "image/jpeg"; 
      bitmap.Save(Response.OutputStream, ImageFormat.Jpeg); 
} 

This is an Normal Image without text

After Add Text

, но не может сохранить изображение текста в к БД. Пожалуйста, помогите мне.

Спасибо.

ответ

0

Код, который вы вставили, касается только добавления текста в растровый объект и сохранения объекта растрового изображения обратно в физический файл, на который добавлен текст. Для сохранения этого изображения в БД нет кода.

+0

Помогите мне сделать это? –

+0

Это довольно просто, в зависимости от того, какие объекты вы используете для сохранения данных в БД. Вы просто обновляете поле таблицы двоичными данными вашего растрового объекта. –

0
//Post method for Image upload 
    [HttpPost] 
      public async Task<JsonResult> AddPromotion(AddPromotionDto addpromotions) 
      { 
       if (Request.Files.Count > 0) 
       { 
        HttpFileCollectionBase files = Request.Files; 
        for (int i = 0; i < files.Count; i++) 
        { 
         HttpPostedFileBase file = files[i]; 
         string promotionImage; 
         addpromotions.PromotionImage = file.FileName; 
         promotionImage = Path.Combine(Server.MapPath("../Image/"), addpromotions.PromotionImage); 
         file.SaveAs(promotionImage); 
         using (var fileStream = new MemoryStream()) 
         { 
          using (var oldImage = new Bitmap(file.InputStream)) 
          { 
           var format = oldImage.RawFormat; 
           string fileName = promotionImage; 
           using (var newImage = ResizeImage(oldImage, 800, 2000)) 
           { 
            Graphics graphicsImage = Graphics.FromImage(newImage); 
            StringFormat stringformat = new StringFormat(); 
            stringformat.Alignment = StringAlignment.Far; 
            stringformat.LineAlignment = StringAlignment.Far; 
            StringFormat stringformat2 = new StringFormat(); 
            stringformat2.Alignment = StringAlignment.Center; 
            stringformat2.LineAlignment = StringAlignment.Center; 
            Color StringColor = System.Drawing.ColorTranslator.FromHtml("#e80c88"); 
            string Str_TextOnImage = addpromotions.PromotionName; 
            graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 40, 
            FontStyle.Regular), new SolidBrush(StringColor), new Point(500, 300), 
            stringformat); 
            Response.ContentType = "image/jpeg"; 
            newImage.Save(fileName, format); // for overwrite the previous image 
           } 
          } 
         } 
        } 
       } 
       await companyManager.AddPromotion(User.Identity.Name, addpromotions); 
       return Json("Promotions", JsonRequestBehavior.AllowGet); 
      } 


    // Method for resize the image 
    public static Bitmap ResizeImage(Bitmap image, int width, int height) 
      { 
       if (image.Width <= width && image.Height <= height) 
       { 
        return image; 
       } 
       int newWidth; 
       int newHeight; 
       if (image.Width > image.Height) 
       { 
        newWidth = width; 
        newHeight = (int)(image.Height * ((float)width/image.Width)); 
       } 
       else 
       { 
        newHeight = height; 
        newWidth = (int)(image.Width * ((float)height/image.Height)); 
       } 
       var newImage = new Bitmap(newWidth, newHeight); 
       using (var graphics = Graphics.FromImage(newImage)) 
       { 
        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
        graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; 
        graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; 
        graphics.FillRectangle(Brushes.Transparent, 0, 0, newWidth, newHeight); 
        graphics.DrawImage(image, 0, 0, newWidth, newHeight); 
        return newImage; 
       } 
      } 
Смежные вопросы