1. 程式人生 > >把圖片儲存到資料庫中和從資料庫中讀取圖片

把圖片儲存到資料庫中和從資料庫中讀取圖片

最近做到一個小專案,其中關係到圖片的一些操作。比如:將圖片儲存到資料庫中、從資料庫中讀取圖片、顯示圖片、列印圖片等。此處對這些在專案中遇到的一些瑣碎知識加以總結,以便日後查詢。

  1、將圖片作為其中的一個引數儲存到資料庫中

  在專案中,一般是將圖片轉換成二進位制流格式,然後儲存到資料庫中。同時資料庫表中儲存圖片的格式一般為image。此次專案,是將圖片作為一個引數,和其他幾個引數一起儲存到資料庫中,和在網上搜索到的圖片儲存不太一樣,此處稍作修改,但都是檢測過的。

  儲存步驟:

  1、搜尋到圖片的路徑

  2、讀取圖片並將圖片轉換成二進位制流格式

  3、sql語句儲存到資料庫中。

   貼程式碼: 

private void btnWrite_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string filePath = ofd.FileName;//圖片路徑
                FileStream fs = new FileStream(filePath, FileMode.Open);
                byte[] imageBytes = new byte[fs.Length];
                BinaryReader br = new BinaryReader(fs);
                imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//圖片轉換成二進位制流

                string strSql = string.Format("insert into [SBS].[dbo].[Model] ([M_QRCode],[M_Skills] ) values (@image,'2')");
                int count = Write(strSql,imageBytes );

                if (count > 0)
                {
                    MessageBox.Show("success");
                }
                else
                {
                    MessageBox.Show("failed");
                }
            }
        }
資料庫連線和儲存圖片語句:
private int Write(string strSql,byte[] imageBytes)
        {
            string connStr = "Data Source=192.168.4.132;initial Catalog=SBS;User ID=sa;Password=sa;";

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, conn))
                {
                    try
                    {
                        conn.Open();
                        SqlParameter sqlParameter = new SqlParameter("@image", SqlDbType.Image);
                        sqlParameter.Value = imageBytes;
                        cmd.Parameters.Add(sqlParameter);
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }
        }

 2、從資料庫總讀取圖片

從資料庫中讀取圖片欄位,並轉換成記憶體流生成bitmap。

  貼程式碼: 

private void btnRead_Click(object sender, EventArgs e)
        {
            string strSql = string.Format("select M_QRCode from [SBS].[dbo].[Model] where M_id = 7");//圖片儲存的欄位是M_QRCode
            Read(strSql);
        }

        private void Read(string strSql)
        {
            string connStr = "Data Source=192.168.4.132;initial Catalog=SBS;User ID=sa;Password=sa;";

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, conn))
                {
                    conn.Open();
                    SqlDataReader sqlDr = cmd.ExecuteReader();
                    sqlDr.Read();
                    byte[] images = (byte[])sqlDr["M_QRCode"];
                    MemoryStream ms = new MemoryStream(images);
                    Bitmap bmp = new Bitmap(ms);
                    pictureBox1.Image = bmp;
                }
            }
        }

3、根據圖片路徑顯示圖片

  這個比較簡單,直接貼出程式碼 

private void btnLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(ofd.FileName);
            }
        }

4、列印圖片

  列印圖片是在將圖片顯示在pictureBox的基礎上進行的。

  步驟:

  1、將printDocument控制元件拖到介面,新增列印程式碼

  2、設定PrintDocument控制元件的Print_PrintPage事件

private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = this.printDocument1;
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    printDocument1.Print();
                }
                catch (Exception ex)
                {
                   printDocument1.PrintController.OnEndPrint(printDocument1, new System.Drawing.Printing.PrintEventArgs());
                }
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(pictureBox1.Image, 30, 30);
        }

 附帶著將圖片轉換成二進位制和將二進位制轉換成圖片專門寫出來,以便於檢視。 

public byte[] ConvertBinary(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);//以檔案流形式讀取圖片
            BinaryReader br = new BinaryReader(fs);//轉換成二進位制流
            byte[] imageBytes = br.ReadBytes((int)fs.Length);//儲存到位元組陣列中

            return imageBytes;
        }

        public void ShowImage(byte[] imageBytes)
        {
            MemoryStream ms = new MemoryStream(imageBytes);
            pictureBox1.Image = Image.FromStream(ms);
        }

在pictureBox中顯示圖片的三種方式: 
public void Method()
        {
            MemoryStream ms;
            pictureBox1.Image = Image.FromStream(ms);

            Bitmap bitmap;
            pictureBox1.Image = bitmap;

            string filePath;
            pictureBox1.Image = Image.FromFile(filePath);
        }

winform中控制元件combobox控制元件使用: 
public void BindCombobox()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("id", typeof(int)));
            dt.Columns.Add(new DataColumn("value", typeof(string)));

            for (int i = 0; i < 3; i++)
            {
                DataRow dr = dt.NewRow();
                dr["id"] = i;
                dr["value"] = 10 + i;
                dt.Rows.Add(dr);
            }

            this.comboBox1.DataSource = dt;
            this.comboBox1.DisplayMember = "value";
            this.comboBox1.ValueMember = "id"; 
        }

        public void ShowValue()
        {
            this.textBox1.Text = this.comboBox1.Text;
            this.textBox2.Text = this.comboBox1.SelectedValue.ToString();
        }



相關推薦

圖片儲存資料庫中和資料庫讀取圖片

最近做到一個小專案,其中關係到圖片的一些操作。比如:將圖片儲存到資料庫中、從資料庫中讀取圖片、顯示圖片、列印圖片等。此處對這些在專案中遇到的一些瑣碎知識加以總結,以便日後查詢。   1、將圖片作為其中的一個引數儲存到資料庫中   在專案中,一般是將圖片轉換成二進位

檔案讀取圖片,與資料庫讀取圖片評測

一、在 d:\ 下建立 image 資料夾,再放10 張圖片, 名稱從 1.png 到 10.png . 二、先建立新庫 db1, 然後按下面指令碼建立初始環境: USE db1 GO IF OBJECT_ID('t_path') IS NOT NULL DROP TABLE t_pat

springboot配置addResourceHandler和addResourceLocations,使得可以磁碟讀取圖片、視訊、音訊等

磁碟目錄 WebMvcConfig的程式碼 //對靜態資源的配置 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { String os = System.ge

快取讀取圖片

上傳頭像圖片時,使用相同的檔名儲存圖片以求覆蓋舊的圖片,當讀取時,由於使用相同的url,瀏覽器就會從快取中讀取圖片,不能實時更新圖片。。。 通過meta指定不儲存cache: <meta http-equiv="pragma" content="no-cache"&

c#向SQL Server儲存圖片並且再資料庫讀取圖片

前言 資料庫課程設計答辯時,老師提出瞭如果資料是圖片或者其他檔案型別的時候,頓時覺得自己做的管理系統用到的較多的就是Char型別。於是,答辯結束後,就蒐集資料學習,在查詢資料的時候發現,有的一開始並不能看懂,找到一篇文件,自己做了一個測試,然後發現出現了一點小

java web將圖片存到儲資料庫資料庫讀取圖片(base64)

一、分析一下基本流程    從前臺頁面獲取圖片,後臺接收圖片檔案轉化成資料,然後儲存到資料庫,然後反向輸出到jsp頁面二、分析一下資料轉換和資料流通  三、將圖片儲存到資料庫中     1、jsp頁面將圖片傳到後臺的過程        jsp頁面將圖片通過form表單提交,後

JAVAExcel讀取資料儲存資料庫

1.jar包 2.資料庫資訊 3.JDBC連線資料庫工具類 package Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedSta

C#將照片或圖片轉化為byte[]存入資料庫資料庫讀照片

publicstaticbyte[] GetBytesByImagePath(string strFile) {byte[] photo_byte =null;using (FileStream fs =new FileStream(strFile, FileMode.Open, FileAcc

java資料庫讀取圖片到Jpanel(用BufferedImage)

import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultS

資料庫思想——資料庫取出日期,獲取日期的月份,並在檢視迴圈顯示

index.php: public function index() { $sql=db('users') ->field('rtime') ->select(); foreach($sql as

20.獲取網路圖片,將圖片儲存在檔案,快取,然後先快取讀取,沒有再檔案讀取

實現的功能主要是標題,那麼接下來我們就分析,如何一步一步的實現這個功能 第一步:建立imgCache資料夾,在裡面建立如下幾個檔案 1.ImgLoaderCallback:用於重新整理ImageView 2.ImageManager:用於管理快取圖片,比如圖片的讀取,還有

使用Bitmap將自身儲存為檔案,BitmapFactoryFile解析圖片並防止OOM

/** 獲得與需要的比例最接近的比例 */ static int calculateInSampleSize(BitmapFactory.Options bitmapOptions, int reqWidth, int reqHeight) { final int height = bitmapOpti

上傳圖片至數據庫及數據庫讀取圖片顯示至頁面

for循環 common 基於 serial 文件創建 每一個 super lis size 1.基於最簡單的servlet+jsp+jdbc實現 2.實驗環境:myeclipse以及tomcat 8.5 3.所需jar包:    4.數據庫:   數據庫用的是mysql

ionic拍照上傳圖片檔案選擇圖片

本文主要使用cordova實現拍照上傳,拍照上傳或從資料夾中選擇上傳圖片 流程:拍照或選擇圖片===>獲取本機路徑==>向伺服器上傳圖片,獲取伺服器上圖片路徑 一、環境準備   安裝 cordova-plugin-camera 外掛     &n

Android呼叫攝像頭拍照儲存,並在相簿選擇圖片顯示

我的配置是: android手機版本是7.0 android studio是3.1 android平臺是9.0 我的測試都是在真機上進行的。 首先來看程式碼: package com.example.sunshunli.cameraalbumtest; import a

ionic呼叫照相機或者相簿選擇圖片進行上傳

開發App的時候會經常用到拍照上傳留作憑證,或者從相簿中選擇。 相關外掛: 相機:cordova-plugin-camera 2.4.1 相簿:cordova-plugin-image-picker 1.1.1 檔案:cordova-plugin-file 許可權:cordova-plugi

網路獲取圖片進行自動輪播

MainActivity package com.example.lunbotu2; import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; impor

網路下載圖片並進行顯示

通過get請求方式獲取網路圖片----主要是方便以後查閱以及做一個筆記 任務要求: 1.新建一個佈局檔案,在佈局檔案中新增Button、ImageView兩個控制元件 2.新建一個GetPictThread實現Runnable介面   (1)定義一個handler用於

JSSDK呼叫微信原生的功能上傳圖片儲存到自己的伺服器

第一件事首先是微信的選擇圖片功能,就是微信發朋友圈選擇圖片的時候那個介面 //呼叫微信拍照功能 wx.chooseImage({ count: 1,

Android相簿選取圖片上傳到阿里雲OSS

    在開發APP軟體中,boss突然提出想在軟體中新增一個多張照片上傳的功能,作為菜鳥的我,琢磨了兩天,才弄出來,今天特地貼出來。本篇部落格主要介紹的是將本地圖片上傳到伺服器的方法技巧。主要技術點是: 一、運用第三方可以從相簿中選取多張圖片。 二、將圖片