簡體   English   中英

如何將 System.Byte[] 轉換為要顯示到 Word C# 中的圖像

[英]How to convert System.Byte[] into an Image to be Displayed into Word C#

我正在努力解決如何處理轉換來自我的 Datagridview 的表中的 System.Byte[] 數組,請參閱包含僅顯示 Sytem.Byte[] 的圖像的列

在此處輸入圖片說明

這是我使用的代碼,但它仍然只顯示文本。

private void ToCsV(DataGridView DGV, string filename)
    {
        try
        {
            if (DGV.Rows.Count != 0)
            {


                int RowCount = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                //add rows
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                    } //end row loop
                } //end column loop



                Document oDoc = new Document();
                oDoc.Application.Visible = true;



                //page orintation
                oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;


                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string oTemp = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";

                    }
                }

                //table format
                oRange.Text = oTemp;

                object Separator = WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders = true;
                object AutoFit = true;
                object AutoFitBehavior = WdAutoFitBehavior.wdAutoFitContent;

                oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                      Type.Missing, Type.Missing, ref ApplyBorders,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);

                oRange.Select();

                oDoc.Application.Selection.Tables[1].Select();
                oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.InsertRowsAbove(1);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();

                //header row style
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                //add header row manually
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                }

                //table style 
                oDoc.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5");
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //header text
                foreach (Section section in oDoc.Application.ActiveDocument.Sections)
                {
                    Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage);
                    headerRange.Text = "your header text";
                    headerRange.Font.Size = 16;
                    headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                }

               /* string fileName = @"C:\Users\JethroPaulo\Desktop\a314bf90a43cb49873d014b00bb3672b.jpg";  //the picture file to be inserted
                Object oMissed = oDoc.Paragraphs[2].Range; //the position you want to insert
                Object oLinkToFile = false;  //default
                Object oSaveWithDocument = true;//default
                oDoc.InlineShapes.AddPicture(fileName, ref  oLinkToFile, ref  oSaveWithDocument, ref  oMissed);

                //Insert text
                Object oMissing = System.Reflection.Missing.Value;
                var oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara1.Range.Text = "First Text";
                oPara1.Range.InsertParagraphAfter();


                Image sparePicture = fetch;
                Clipboard.SetDataObject(sparePicture);
                var oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing);
                oPara2.Range.Paste();
                oPara2.Range.InsertParagraphAfter();*/
                //save the file
                oDoc.SaveAs(filename);

                //NASSIM LOUCHANI
            }
        }
        catch (Exception ex)
        {
            DialogResult result = MessageBox.Show(ex.Message.ToString(), "Critical Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }
    }

你沒有完全復制我的答案,你錯過了ByteArrayToImage

Image sparePicture = ByteArrayToImage(fetch); //<-- This is what you're missing
Clipboard.SetDataObject(sparePicture);
var oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara2.Range.Paste();
oPara2.Range.InsertParagraphAfter();

...

public Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (MemoryStream ms = new MemoryStream(byteArrayIn))
    {
      Image returnImage = Image.FromStream(ms);
      return returnImage;
    }
}

你沒有顯示fetch是什么,但我假設它是一個byte[] ,所以要實現這個:

int r = 0;
for (int c = 0; c <= ColumnCount - 1; c++)
{
    for (r = 0; r <= RowCount - 1; r++)
    {
        if (c == 5) { //Change the constant 5 to use the Student_Image column index
           DataArray[r, c] = ByteArrayToImage(DGV.Rows[r].Cells[c].Value);
        }
        else {
           DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
        }
    }
} 

傑里米先生的想法很有幫助。 我發現的缺失部分如下:

  1. 對象缺失值 - 此對象指的是一個表,該表具有指定的單元格,圖像將被放置到該單元格中。 [Document.Table[1].Cells(row, col).Range]
  2. 圖像備用圖片 - 而不是使用 Object[,] DataArray(參見上面前面的代碼),我使用了一個 Image 對象來存儲圖像數組,然后在剪貼板上設置並粘貼它。
  3. InsertParagrahAfter() - 使用這種方法,我將圖像一張一張地插入到指定的單元格中,就像在 dataGridview 中一樣。

     for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { if (c == 5) { Object oMissing = oDoc.Tables[1].Cell(r + 2, 6).Range; //the position where you want to put the images Image sparePicture = ByteArrayToImage((byte[])DGV.Rows[r].Cells[c].Value); Clipboard.SetImage(sparePicture); Word.Paragraph oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Paste(); oPara2.Range.InsertParagraphAfter(); } } }

幾個小時后,我創建了 Encode 和 Serialize,這將返回一個字符串,其中包含您應用於 img 的 src。

    string img_src = data.Rows[0].IsNull("PHOTO") ? string.Format("") : string.Format("data:image/jpeg;base64,{0}", data.Rows[0]["PHOTO"].EncodeAndSerialize().Replace("\"", ""));
----------------------------    
        public static string EncodeAndSerialize<T>(this T obj) where T : new()
                {
                    var settings = new JsonSerializerSettings
                    {
                        ContractResolver = new HtmlEncodeResolver(),
                        Formatting = Newtonsoft.Json.Formatting.None
                    };
                    return JsonConvert.SerializeObject(obj, settings);
                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM