简体   繁体   English

如何将PNG从Web加载到TImage控件中?

[英]How do I load png from web into TImage control?

I have several small .PNG pictures I wan't to load from a web-address and into TImage images in my application. 我有几张小的.PNG图片,我不想从Web地址加载到应用程序的TImage图像中。 The pictures are "dynamic", so I don't want to "hardcode" them into my app by using TImageList etc. 图片是“动态的”,所以我不想通过使用TImageList等将它们“硬编码”到我的应用程序中。

I have seen several examples, but none of them can give me a straight way to do this. 我已经看到了几个示例,但是没有一个示例可以为我提供直接的方法。

I know I can use TWebBrowser to solve this, but it seems to obscure my application and is not aligned to the alignment i set it to either. 我知道我可以使用TWebBrowser来解决此问题,但是它似乎使我的应用程序晦涩难懂,并且与我将其设置为两者的对齐方式不一致。

Any good suggestions ? 有什么好的建议吗?

My platform is Android, I am using Embarcadero C++Builder XE8 / Appmethod 1.17 我的平台是Android,我正在使用Embarcadero C ++ Builder XE8 / Appmethod 1.17

In FireMonkey, the FMX.Graphics.TBitmap class handles multiple image formats, including PNG. 在FireMonkey中, FMX.Graphics.TBitmap类处理多种图像格式,包括PNG。 The FMX.Objects.TImage component has a Bitmap property . FMX.Objects.TImage组件具有Bitmap属性 All you have to do is use Indy's TIdHTTP component (or any other HTTP API/library of your choosing) to download the PNG image data into a TMemoryStream , and then you can call the TImage::Bitmap::LoadFromStream() method to load the stream data for display, for example: 您所要做的就是使用Indy的TIdHTTP组件(或您选择的任何其他HTTP API /库)将PNG图像数据下载到TMemoryStream ,然后可以调用TImage::Bitmap::LoadFromStream()方法进行加载要显示的流数据,例如:

TMemoryStream *strm = new TMemoryStream;
IdHTTP1->Get(L"http://domain/image.png", strm);
strm->Position = 0;
Image1->Bitmap->LoadFromStream(strm);

Since downloading from a remote server can take time, and you should never block the UI thread, you should use a worker thread to handle the download, for example: 由于从远程服务器下载可能会花费一些时间,并且您永远不应阻止UI线程,因此应使用辅助线程来处理下载,例如:

class TDownloadThread : public TThread
{
protected:
    virtual void __fastcall Execute()
    {
        TIdHTTP *Http = new TIdHTTP(NULL);
        Http->Get(L"http://domain/image.png", Strm);
        Strm->Position = 0;
    }

public:
    TMemoryStream *Strm;

    __fastcall TDownloadThread()
        : TThread(true)
    {
        FreeOnTerminate = true;
        Strm = new TMemoryStream;
    }
};

void __fastcall TMyForm::DownloadImage()
{
    TDownloadThread *Thread = new TDownloadThread();
    Thread->OnTerminate = &DownloadThreadFinished;
    Thread->Start();
}

void __fastcall TMyForm::DownloadThreadFinished(TObject *Sender)
{
    TDownloadThread *Thread = static_cast<TDownloadThread*>(Sender);
    if (!Thread->FatalException)
        Image1->Bitmap->LoadFromStream(Thread->Strm);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM