Conversion of bank image to use in a background

Asked

Viewed 75 times

2

I am using the following code to put buttons with each category name, however I am not able to (I am not able to search) convert the background image, just give me the tostring option.

        {
            ctx.DefaultContainerName = "kinectEntities";

            Console.WriteLine("View criada.. parametro = " + id);

            //cria a query geral.. "select * from produtos"
            ObjectSet<produtos> query = ctx.CreateObjectSet<produtos>();

            //cria a query com o where "select * from produtos where id_categoria = ?"
            var query2 = query.Where("it.id_categorias = @categoria");

            //adiciona o parametro na query2 select * from produtos where id_categoria = 7"
            query2.Parameters.Add(new ObjectParameter("categoria", id));

            foreach (produtos r in query2)
            {
                //percorrendo registros da base
                var button = new KinectTileButton { Label = (r.valor).ToString(CultureInfo.CurrentCulture), Tag = r.id,
                --->Background = r.imagem.ToString()<----};
                button.Click += KinectTileButtonClick;
                this.wrapPanel.Children.Add(button);
            }

2 answers

1


- For images saved in the database as Base64 -

I believe the image was saved as an array of bytes (data format).

So, do it this way:

Put this method in some helper class or inside your code-Behind or somewhere you can easily access.

public static ImageBrush GetBrushFromImage(byte[] imageData)
{
   ImageBrush brush;
   BitmapImage bi;
   using (var ms = new MemoryStream(imageData))
   {
       brush = new ImageBrush();

       bi = new BitmapImage();
       bi.BeginInit();
       bi.CreateOptions = BitmapCreateOptions.None;
       bi.CacheOption = BitmapCacheOption.OnLoad;
       bi.StreamSource = ms;
       bi.EndInit();
   }

   brush.ImageSource = bi;
   return brush;
}

Then call him that:

foreach (produtos r in query2)
{
   //percorrendo registros da base
   var button = new KinectTileButton { Label = (r.valor).ToString(CultureInfo.CurrentCulture), Tag = r.id, 
   Background = GetBrushFromImage(Convert.FromBase64String(r.Image))};
   button.Click += KinectTileButtonClick;
   this.wrapPanel.Children.Add(button);
}

- For images saved as URI (path to resource) -

public static ImageBrush GetBrushFromImageUri(string uri)
{
   return new ImageBrush(new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute)));
}

Then call it that:

foreach (produtos r in query2)
{
   //percorrendo registros da base
   var button = new KinectTileButton { Label = (r.valor).ToString(CultureInfo.CurrentCulture), Tag = r.id, 
   Background = GetBrushFromImageUri(r.Image)};
   button.Click += KinectTileButtonClick;
   this.wrapPanel.Children.Add(button);
}
  • the image was saved as string in the base, only takes the path on the server.

  • Okay, so this string means that it’s been converted to an array of bytes, right? If so, the solution I put in place works.

  • I need to take the string and display it as an image in the background of the button, or I don’t know if I understand you :S

  • You need to convert this string to an object of type Image, which is the type that Background accepts. Just think of it as a type conversion. Test the code and see if it works.

  • I made an edition with an example of your code.

  • Gave error :/Error 3 Cannot implicitly Convert type 'System.Drawing.Image' to 'System.Windows.Media.Brush' E: Usuario Documents Visual Studio 2012 Clean Showcase Views Homescreenview.xaml.Cs 39 34 Showcase

  • I changed the answer, take a look

  • No suitable image generation components to complete this operation were found. : / @Murarialex

  • Are you using WPF, corrreto? Show me the code that saves the image in the database, confirm that it is being saved in the array of bytes format.

  • Schema::create('products',Function(Blueprint $table){ $table->increments('id'); $table->string('Description'); $table->decimal('value',10,2); $table->integer('id_categories')->unsigned(); $table->string('picture')->nullable(); saved as string $table->timestamps();

  • I changed the answer. Try it this way Background = GetBrushFromImage(Convert.FromBase64String(r.Image))};

  • Another error :/ to almost giving up :/ Input is not a valid Base 64 character string, as it contains a non-base 64 character, more than two fill characters, or an illegal character between fill characters.

  • Search and find out what format the image is in the bank. Look at this string in the bank and tell me if that string is a Base64, it’s a URI, what it is.

  • in the database I saved only the image path on my server, for example public/Vj3a97ucxnrjudvtolumo1yil67br0ung3xienst.jpg || in the database is varchar(191) utf8mb4_unicode_ci

  • Ah, now it all makes sense, you keep the image’s URI. I’ll edit the answer.

  • Okay, look at the change at the end

  • Could not locate part of path. However error shows the correct image path

  • In your code, you will need to adjust the path to get the complete path to the directory where the image is. Ex.: AppDomain.CurrentDomain.BaseDirectory + uri in the Getbrushfromimageuri method. The answer is right, you just have to adjust it so that it finds the correct path.

  • I tried to do this to get my directory. public Static Imagebrush Getbrushfromimageuri(string Uri) {&#xA; var imageFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, &#xA; "C:\Bitnami\wampstack-5.6.30-2\apache2\htdocs\mvc\public\images");&#xA; var firstFile = Directory.EnumerateFiles(imageFolder, "*.jpg")&#xA; . Firstordefault(); Return new Imagebrush(new Bitmapimage(new Uri(imageFolder,Urikind.Relativeorabsolute)); }

  • In debug, put a break point on the line where it mounts the path name and see if it is correct. If it’s not, keep adjusting... now it’s just a few more

Show 15 more comments

0

Solved @Murarialex, thank you so much for your help!

Follow the code I used to solve my problem:

public static ImageBrush GetBrushFromImageUri(string uri)
{
    string filePathRelativeToAssembly = Path.Combine(
        @"C:\Bitnami\wampstack-5.6.30-2\apache2\htdocs\mvc\public",
        uri
    );

    string normalizedPath = Path.GetFullPath(filePathRelativeToAssembly);

    return new ImageBrush(
        new BitmapImage(
            new Uri(normalizedPath,UriKind.RelativeOrAbsolute)
        )
    );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.