无法将类型对象(即位图)转换为位图

时间:2018-09-19 20:14:03

标签: c# casting bitmap

我有以下代码:

using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DlibDotNet;
using DlibDotNet.Extensions;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace MyNamespace.CompVis.FaceSwap
{
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    public MainForm(string title, Bitmap bitmap)
    {
        this.Text = title;
        pictureBox = new PictureBox();
        this.Controls.Add(pictureBox);
        pictureBox.Dock = DockStyle.Fill;
        pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
        pictureBox.Image = bitmap;
    }
    private void MainForm_Load(object sender, EventArgs e)
    {
        // load the input image
        string sPathTemplate = "d:\\facewarp2\\heads\\template.jpg";
        System.Drawing.Bitmap nBmpTemplate = Bitmap.FromFile(sPathTemplate) as Bitmap;

        string sPathIntruder = "d:\\facewarp2\\heads\\swap.jpg";
        System.Drawing.Bitmap nBmpIntruder = Bitmap.FromFile(sPathIntruder) as Bitmap;

        // process image
        System.Drawing.Bitmap newBitmap = ProcessImage(nBmpTemplate, nBmpIntruder);
    }

    private System.Drawing.Bitmap ProcessImage(System.Drawing.Bitmap uTemplateImage, System.Drawing.Bitmap uIntruderImage)
    {
         System.Drawing.Bitmap nClone = uTemplateImage.Clone();

最后一行失败。编译器告诉我

The type "object" can't be implicitely cast to "System.Drawing.Bitmap". An explicit conversion exists (possible a conversion is missing).

我的代码有什么问题?

1 个答案:

答案 0 :(得分:2)

Clone方法返回一种对象。

但是nClone的类型为Bitmap。

以防万一,您应该使用

Bitmap nClone = (System.Drawing.Bitmap) uTemplateImage.Clone();