Laman

Rabu, 21 Juli 2010

Gambar di MySql (C#)

Alhamdullilah.
Setelah beberapa menyelesaiakan projek menyimpan gambar di database mySql, Akhirnya selesai juga, "Bisa Karena Biasa" kata-kata itu yang membuat kita termotivasi untuk tidak nyerah dalam memperdalam pengatahuan tentang C#. Oke sekarang kita langsung ke persoalan, dalam beberapa kasus misal di sistem informasi terkadang kita sangat membutuhkan yang namanya image suatu data, misalnya kita menggunakan sistem informasi pegawai, biasanya photo pegawai akan di butuhkan untuk memperjelas dan untuk mempermudah user dalam mengelola dan menelaah informasi

Sebenarnya seperti contoh kasus di atas, banyak orang memakai teknik filesystem. Maksudnya file atau photo yang telah kita upload (pada aplikasi berbasis dekstop) atau yang telah ditambahkan (dalam aplikasi berbasis dekstop) di simpan di suatu folder, ini adalah teknik yang paling sering di gunakan, karena tidak begitu rumit dan tidak ada teknik khusus dalam mengelolanya, tapi jika kita membutuhkan attribut tambahan dalam mengelola file photo tersebut kita akan kesulitan dalam memanage nya



Untuk itu file photo yang sudah ditambahkan akan lebih mudah di menage jika di simpan dalam database(sql server, mysql, oracle, dbase dll). sebenarnya tidak sulit dalam melakukan penyimpanan image ke dalam suatu DBMS, yang perlu di perhatikan hanyalah bahwa image tidak bisa langasung di simpan kedalam DBMS, kita harus mengkonvertnya terlebih dahulu ke dalam type blob, karena hampir semua DBMS mempunyai type data ini
berikkut adalah potongan script untuk mengkonvert image yang ditambahkan oleh user dan sekaligus menyimpannya kedalam database
private void File2SqlBlob(string SourceFilePath)
{
 try
  {
  MySqlConnection cn = new MySqlConnection(connectionSQL);
  MySqlCommand cmd = new MySqlCommand("INSERT into        image(gambar) values (?Picture)", cn);
  System.IO.FileStream fs = new        System.IO.FileStream(SourceFilePath, System.IO.FileMode.Open,    System.IO.FileAccess.Read);

  Byte[] b = new Byte[fs.Length];
  fs.Read(b, 0, b.Length);
  fs.Close();
  MySqlParameter P = new MySqlParameter("?Picture", MySqlDbType.LongBlob, b.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, b);
  cmd.Parameters.Add(P);
  cn.Open();
  if (cmd.ExecuteNonQuery() == 1)
  MessageBox.Show("Your images stored successfully");
  cn.Close();
  }
  catch (MySqlException ex)
  {
  MessageBox.Show(ex.Message);
  }
 }

Sedangkan script dibawah ini adalah function untuk mengkonvert image ke blob 


 public static byte[] GetPhoto(string filePath)
        {
            FileStream fs = new FileStream(filePath,     FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);


            byte[] photo = br.ReadBytes((int)fs.Length);


            br.Close();
            fs.Close();


            return photo;
        }



Berikut ini adalah contoh bila kita benar dalam melakukan pengkonvertan photo, dan melakukan penyimpanan dalam database


untuk file lengkapnya bisa download disini
jika ada yang tertarik dan belum jelas, 
silahkan contact us on informasi@csharp-indonesia.com

53 komentar:

  1. 1) apa itu parameterdirection.input dan datarowversion.current??..adakah suda initialize daripada awal...ataupon memang dlm library....

    2) (?picture) itu sebenarnya apa?.
    adakah image path??..macam mana mahu ditulis???

    BalasHapus
  2. 1) semua source code ditulis murni menggunakan source asli C#, tidak menggunakan library.

    2) dalam koneksi dotNet(dalam hal ini C#) dengan mysql banyak cara penulisan parameter, ?picture merupakan salah satu penulisan dimana ?picture merupakan variabel yang nantinya akan diisi pada baris selanjutnya

    BalasHapus
  3. boleh tak entry akan datang kamu buat connect c# ke facebook...kerana saya ada banyak masalah...saya perlu buat project membuat desktop application tentang sistem rumah anak-anak yatim..di dalamnya ada ruangan untuk facebook..tp still tak dapat connect ke facebook kerana code yang tak bertepatan..

    BalasHapus
  4. boleh

    regard,
    okfan rizal ferdiansyah

    BalasHapus
  5. klo save dan load image dari database M. access gmn? saya butuh bantuannya ya...

    klo udah bisa, ni emailq satria_candra_prastowo@yahoo.co.id

    BalasHapus
  6. jika data gambar ingin di simpan di DBMS Microsoft acces, sebenarnya tidak ada masalah. Hanya mengganti tempat pemyimpanannya saja (dalam hal ini dari MYSQL ke MS Acces). Tetapi saya kurang tahu apakah MS ACCES ada type data blob. seingat saya sich ada.... untuk koneksinya ganti aja dengan ODBC. Insyaallah secepatnya akan saya post tentang penyimpanan gambar di MS Acces

    BalasHapus
  7. pak.. saya masukin gambar yg resolusinya besar kok tulisan nya data too long for column 'gambar' at row 1. gmn solusinya ya pak?

    BalasHapus
  8. csharp-indonesia.com20 Maret 2012 16.13

    sebelumnya saya minta maaf karena terlalu lama mereply komen saudara,
    begini saya jelaskan terlebih dahulu tentang dataGrid, untuk jumlah rows tidak ada batasannya, sehingga semakin tinggi memori komputer saudara semakin besar jumlah maksimal dari rows yang saudara buat, akan tetapi untuk colomn ada batasannya, tepatnya saya lupa tapi kira kira sekitar 3-6 ribu colomn.

    kaitannya dengan error yang saudara alamai adalah terlalu besar resolusi yang saudara masukan, ini bisa saya pastikan bahwa lebar/width pada gambar saudara melebihi dari batas colomn pada datagridview. untuk mengatasi masalah ini saudara hilangkan source code untuk menampilkan nilai piksel yang ada didatagrid,
    terimakasih semoga bisa membantu

    BalasHapus
  9. klw pake sql server gimana

    BalasHapus
  10. untuk sql server sama saja, diDBMS apapun selalu menyediakan type data bloob. intinya adalah melakukan conversi type data image ke type data bloob selanjutnya menyimpan file image yang sudah dikonversi ke blob ke DBMS selayaknya menyimpan text ke DBMS

    jadi walaupun berbeda DBMS yang digunakan, saya rasa yang perlu dirubah adalah koneksi string antra DBMS dan program, bukan programnya.
    terimakasih
    semoga bisa membantu dan bermanfaat

    BalasHapus
  11. gan bisa dijelasin perbaris dari sintak insert kebawah, koq proses nyimpannya panjang sekali, dan bingung dengan sintaks nya

    thanks

    BalasHapus
  12. Kalo belajar dari dasar dari mana harus saya mulai

    BalasHapus
    Balasan
    1. dari filomenaweb.com , disana ada tutorial c# dasar

      Hapus
  13. I was working and suddenly I visits your site frequently and recommended it to me to read also. The writing style is superior and the content is relevant. Thanks for the insight you provide the readers!

    Signature:
    i like play games happy wheels online and play happy wheels 2 games and Download retrica online includes more than eighty different filters with many different styles and include retrica indir , and zombie tsunami is the ideal game for anyone who loves the running game genre

    BalasHapus
  14. Thanks for sharing. I hope it will be helpful for too many people that are searching for this topic.Signature:
    messenger indir | messenger indir | messenger | messenger dowload | messenger indir | messenger | messenger indir | messenger download

    BalasHapus
  15. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    monkey go happy 2cat mario 2learn to fly 2 | happy wheels demo | mahjong online | pacman game | monkey go happy 3 | cat mario 3learn to fly 3 | happy wheels 2 | mahjong | pacman games

    BalasHapus
  16. gan kalu ada tutorial gambar c# ke sql server mohon di upload gan, thanks

    BalasHapus
  17. I would like more information about this, because it is very nice. Thanks for sharing!
    baixar facebook gratis
    baixar whatsapp gratis
    temple run 2
    traffic rider

    BalasHapus
  18. Thanks for your sharing. Your article is very useful, it gives me more understanding. Please allow me to share a few:
    Unblocked Games - Score Hero - Photo Grid - baixar facebook

    BalasHapus
  19. Thank you for such a sweet tutorial - all this time later, I've found it and love the end result. I appreciate the time you spent sharing your skills.
    cookie clicker | dream league soccer | crossword puzzles | dream league soccer | crossword puzzles game | dream league soccer apk | cookie clicker

    BalasHapus
  20. You need to have time to take care of the active. It in fact was a amusement account it. Look advanced to far added agreeable from you.
    banana kong ,
    banana kong baixar ,
    baixar banana kong ,
    download banana kong ,
    banana kong

    BalasHapus
  21. Your article helped me together multiple views on the matter. In life there are a lot of the stress and fatigue, you just visit my website or games and apps for your phone

    clash royale game, clash royale apk , download clash royale , clash royale

    BalasHapus
  22. Life becomes more interesting and wonderful when you share your memorable moments with friends and family through unique photographs. You can create your own unique style impressed with image editing software. And after hours of work stress you can also
    dr driving, dr driving baixar ,download dr driving, dr driving

    BalasHapus
  23. Life becomes more interesting and wonderful when you share your memorable moments with friends and family through unique photographs. You can create your own unique style impressed with image editing software. And after hours of work stress you can also

    tank trouble, tank trouble 2, tank trouble games, tank trouble

    BalasHapus
  24. Mostly people have all the same things when they are writing academic task or any other writing, especially light music most people like during the writing.
    dream league soccer download , dream league soccer apk , download dream league soccer , dream league soccer

    BalasHapus
  25. Mostly people have all the same things when they are writing academic task or any other writing, especially light music most people like during the writing.

    subway surf , baixar subway surf, subway surf download , download subway surf

    BalasHapus
  26. Thanks I have read your article, it is very interesting and exciting
    download go launcher, go launcher apk, go launcher , go launcher androi,

    BalasHapus
  27. E-mail plays an indispensable role in work and everyday life. Today there are many birth webmail services to meet basic needs. However, I would recommend to everyone webmail service is great, almost as soon as available on the market
    Hotmail Iniciar Sesión , Iniciar Sesión Hotmail , hotmail

    BalasHapus
  28. Your blog posts are more interesting and impressive. I think there are many people like and visit it regularly, including me.I actually appreciate your own position and I will be sure to come back here.
    outlook iniciar sesión l iniciar sesión outlook l outlook l iniciar sesión

    BalasHapus
  29. This blog is so nice to me. I will continue to come here again and again. Visit my link as well. Good luck
    http://www.jualobataborsiherbal.com/ obat aborsi
    http://caramenggugurkankandungan.info/ cara menggugurkan kandungan
    http://www.jualobataborsiherbal.com/cara-menggugurkan-kandungan/ cara menggugurkan kandungan
    http://jualobatpenggugurkandungan.net/ obat penggugur kandungan
    http://tandatandakehamilan.net/ tanda tanda kehamilan
    http://tandatandakehamilan.net/cara-cepat-dan-selamat-menggugurkan-kandungan/ cara menggugurkan kandungan
    http://obataborsi59.com/ obat aborsi
    http://obattelatdatangbulan.info/ obat telat datang bulan
    http://klinikobataborsi.com/ jual obat aborsi

    BalasHapus
  30. Offre una varietà di replica orologi , tra cui Rolex, Omega, Breitling, Panerai e altre repliche di orologi di lusso
    Offre orologi replica e falsi orologi Rolex replica a prezzi convenienti.

    BalasHapus
  31. Yellow gold used hour-markers and rolex replica Royal Oak hands with bright finishing total this standout watch. We personally advise the Royal rolex replica Oak Chronograph to gentlemen who are not scared to stick to a more conservative design however still desire something streamlined and fake rolex attractive.

    BalasHapus
  32. Questa è la prima volta che viene rilasciato al pubblico,orologi repliche l'orologio Blancpain, o il dono che le è stato dato dal terzo marito di Marilyn Monroe, lo scrittore Arthur Miller. L'orologio è realizzato in platino con 71 diamanti a taglio rotondo e due diamanti a taglio oliva.replica rolex Il quadrante rettangolare bianco è stampato con il logo "Blancpain" ed è dotato di indici gialli e lancette blu. L'orologio è dotato di un movimento meccanico in miniatura FHF59 inciso con le parole "Rayville Watch Company con 17 cuscinetti gioiello".IWC replica Che si tratti di indossare tutti i giorni durante il giorno o scintillare alla festa notturna,hublot replica il delicato aspetto geometrico e il design di questo prezioso orologio riflettono il perfetto equilibrio tra avanguardia all'avanguardia e romanticismo elegante.orologi replica Unisce la femminilità, la creatività unica e il temperamento glamour in un modo ineguagliabile, proprio come lo stesso Marilyn Monroe, un simbolo di una vera aura eterna.

    BalasHapus
  33. Questa ispirazione ispirata allo stile Art Déco, nata negli anni '30, è l'orologio del marchio all'asta, che è legato ad altri oggetti personali di Monroe, tra cui abiti, libri, una sedia da regista e gli Stati Uniti.replica rolex Tessera associativa sindacale, cartoleria,panerai replica ricevuta di denaro di Monroe quando vive a New York e diversi ritratti di Monroe con la firma di Lawrence Schiller (anche il fotografo stesso ha visitato la cerimonia di apertura) Presenta la straordinaria eccellenza e la complessa personalità di questa leggendaria attrice.replica orologi Questi oggetti intimi sono le mostre principali della Retrospettiva di orologi da donna Blancpain,hublot replica presentata in un ambiente raffinato ed elegante.

    BalasHapus
  34. At this point, I am years beyond getting mad at brands who step out of their groove in search of a more exciting product.replica watches One exception, though, is that I do factor in how said product is officially presented by its manufacturer. Because we are by nature (as well as modern cosmopolitan life) wired to be mad about something all the time, I, in turn, find myself getting mad at brands who do nothing exciting at all. I am thinking about all those once-great companies that have taken a head-first dive into their archives and haven’t returned since, as far as their more affordable products are concerned. (Just look at Jaeger-LeCoultre,replica watches uk Tudor or Montblanc; and I am still hoping that TAG Heuer won’t become a fully fledged member of this group of lazy and/or direction-lacking brands.)

    BalasHapus