2016-08-25 46 views
0

我必須在圖片框中顯示圖像。這些圖像是檔案的高分辨率掃描。由於這個高分辨率,我的平移和縮放功能非常緩慢。爲了解決這個問題,我減少了位圖的寬度和長度,同時保持圖像的可讀性。在我的代碼drawOriginalImage();變量「質量」因此是我減小位圖大小的因素。這就是我的做法:如何使用backgroundworker加載圖像並將其顯示到圖框?

private void drawOriginalImage(int quality) { 
    try { 
     int x = originalImage.Width/quality, 
      y = originalImage.Height/quality; 
     pictureBox.Image = (Image)new Bitmap(originalImage, x, y); 
     pictureBox.SizeMode = PictureBoxSizeMode.Zoom; 
    } 
    catch (Exception ex) { 
     throw ex; 
    } 
} 

但是這種解決方案帶來了另一個問題。此步驟可能會很長:

pictureBox.Image = (Image)new Bitmap(originalImage, x, y); 

由於此緩慢,我想用Backgroundworker功能處理此步驟。現在我的代碼如下所示:

private void drawOriginalImage(int quality) { 
    Cursor = Cursors.AppStarting; 
    backgroundWorker.RunWorkerAsync(new Point(
     originalImage.Width/quality, 
     originalImage.Height/quality 
    )); 
} 
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { 
    Point p = (Point)e.Argument; 
    e.Result = new Bitmap(originalImage, p.X, p.Y); 
} 
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { 
    if (e.Error != null) { 
     MessageBox.Show("Image too big.\nOriginal error:\n" + e.Error); 
    } 
    else { 
     pictureBox.Image = (Image)e.Result; 
     pictureBox.SizeMode = PictureBoxSizeMode.Zoom; 
     Cursor = Cursors.Default; 
    } 
} 

但它不起作用。我看到光標從「Cursors.AppStarting」更改爲「Cursors.Default」,因此任務可能已完成。但我的影像箱裏沒有圖像?怎麼可能?我究竟做錯了什麼?

當我調試它時,程序永遠不會進入「backgroundWorker_RunWorkerCompleted」。怎麼會這樣?

回答

1

我已經找到它了。我已經正確地把我所有的事件都加上了這個:

backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork); 
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted); 
相關問題