0

在构建图像时,我得到了关于invalidOperationExceptionin的奇怪信息。PresentationCore.dllgcnew Image()

我附上项目和JPG文件(可以放入C:\)它实际上无法以其他方式检查,因为项目(引用)的配置需要很长时间,并且只是复制代码不起作用。

http://www.speedyshare.com/Vrr84/Jpg.zip

我该如何解决这个问题?

在此处输入图像描述


 // Jpg.cpp : Defines the entry point for the console application.
    //

#include "stdafx.h"
#using <mscorlib.dll> //requires CLI
using namespace System;
using namespace System::IO;
using namespace System::Windows::Media::Imaging;
using namespace System::Windows::Media;
using namespace System::Windows::Controls;
int _tmain(int argc, _TCHAR* argv[])
{


    // Open a Stream and decode a JPEG image
        Stream^ imageStreamSource = gcnew FileStream("C:/heart.jpg", FileMode::Open, FileAccess::Read, FileShare::Read);
        
        JpegBitmapDecoder^ decoder = gcnew JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions::PreservePixelFormat, BitmapCacheOption::Default);
        BitmapSource^ bitmapSource = decoder->Frames[0];//< --mamy bitmape
    
        // Draw the Image
        Image^ myImage = gcnew Image();//<----------- ERROR
        myImage->Source = bitmapSource;
        myImage->Stretch = Stretch::None;
        myImage->Margin = System::Windows::Thickness(20);
        //

        int width = 128;
        int height = width;
        int stride = width / 8;
        array<System::Byte>^ pixels = gcnew array<System::Byte>(height * stride);

        // Define the image paletteo
        BitmapPalette^ myPalette = BitmapPalettes::Halftone256;

        // Creates a new empty image with the pre-defined palette.
        BitmapSource^ image = BitmapSource::Create(
           width, height,
           96, 96,
           PixelFormats::Indexed1,
           myPalette,
           pixels,
           stride);

        System::IO::FileStream^ stream = gcnew System::IO::FileStream("new.jpg", FileMode::Create);
        JpegBitmapEncoder^ encoder = gcnew JpegBitmapEncoder();
        TextBlock^ myTextBlock = gcnew System::Windows::Controls::TextBlock();
        myTextBlock->Text = "Codec Author is: " + encoder->CodecInfo->Author->ToString();
        encoder->FlipHorizontal = true;
        encoder->FlipVertical = false;
        encoder->QualityLevel = 30;
        encoder->Rotation = Rotation::Rotate90;
        encoder->Frames->Add(BitmapFrame::Create(image));
        encoder->Save(stream);
    return 0;
}
4

1 回答 1

2

核心问题在那里:

调用线程必须是 STA [...]

您的主线程必须标记为单线程单元(简称 STA),WPF 才能正常运行。修复?添加[System::STAThread]到您的_tmain,从而通知运行时主线程必须是 STA。

[System::STAThread]
int _tmain(int argc, _TCHAR* argv[])
{
    // the rest of your code doesn't change
}
于 2012-11-22T00:36:26.523 回答