对于移动应用程序,我需要能够使用 Flex 4.5 将图像保存和加载到 SQLite 数据库中。用例是这样的:

  • 在 View 内部有一个带有 URL 作为源的 spark Image 对象
  • 当用户单击按钮时,图像将保存到 BLOB 字段内的 SQLite 数据库中。
  • 在单独的 Image 中,source 设置为存储在 db 中的 ByteArray。

  • 迄今为止最大的问题是:我从哪里获得已加载图像的 ByteArray?我试过调试和检查 Image、BitmapImage 和 BitMapData 但没有字节数组的迹象......也许它在 ContentLoader 内部?但除非我启用缓存,否则这是空的。

    我已经做了一些研究,但没有完整的例子来说明如何处理这个问题。我编写了一个简单的 View ,任何人都可以将其复制并粘贴到新项目中。它将编译而不会出错,并可用于测试。当我得到我需要的答案时,我将更新此代码,以便任何人都可以拥有此工作流程的完整示例。唯一的警告:我使用到数据库的同步连接来避免使用事件处理程序使代码复杂化,我希望它尽可能简单。

    一旦它在两种方式都完全正常运行,我只会将此问题标记为已回答。

    更新九月。 2011 年 9 月:

    下面的代码现在在两个方向(保存和加载)都完全起作用。以下是我学到的一些东西:
  • 原来可以在图像本身的 LoaderInfo 中找到 spark Image 的 ByteArray。像这样:


  • 但是,尝试将此 ByteArray 设置为另一个图像的源( image2.source = image1.loaderInfo.bytes )会导致此安全错误:


  • 这太糟糕了,因为它会节省很多时间和处理能力。 如果有人知道如何克服这个错误,将不胜感激!
  • 无论如何,解决方法是使用 JPEGEncoder 或 PNGEncoder 对 ByteArray 进行编码。我使用了 JPEGEncoder,它生成的文件要小得多。方法如下:


  • 现在的问题是将这些字节保存到数据库中。一旦我们读出它们,将它们保存为现在的样子就行不通了,我不知道为什么。所以解决方案是将它们编码成这样的 base64 字符串:


  • 现在只需将该字符串保存到 BLOB 字段中,然后再将其读出。但是,您必须像这样将它从 base64 字符串解码为 ByteArray:


  • 现在将 bytearray 指定为图像的来源,您就完成了。简单吧?
  • 感谢所有提供帮助的人,如果您发现任何优化或替代方法,请发表评论。如果需要,我会回复并更新此代码。

  • 注意:以下代码功能齐全。
    <?xml version="1.0" encoding="utf-8"?>
    <s:View
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        actionBarVisible="false"
        creationComplete="init(event)">
    
        <s:layout>
            <s:VerticalLayout />
        </s:layout>
    
        <s:TextArea id="logOutput" width="100%" height="200" fontSize="10" editable="false" />
    
        <s:Image id="remoteImage" source="http://l.yimg.com/g/images/soup_hero-02.jpg.v1" enableLoadingState="true" />
    
        <s:Button label="Save Image" click="saveImage()" />
    
        <s:Image id="savedImage" source="" enableLoadingState="true" />
    
        <s:Button label="Load Image" click="loadImage()" />
    
        <s:Button label="Copy Image" click="copyImage()" />
    
        <fx:Script>
            <![CDATA[
                import mx.core.FlexGlobals;
                import mx.events.FlexEvent;
                import mx.graphics.codec.JPEGEncoder;
                import mx.utils.Base64Decoder;
                import mx.utils.Base64Encoder;
    
                public var dbName:String;
                public var file:File;
                public var sqlConnection:SQLConnection;
    
                import spark.components.supportClasses.StyleableTextField;
    
                protected function init(event:FlexEvent):void
                {
                    dbName = FlexGlobals.topLevelApplication.className+".db";
                    file = File.documentsDirectory.resolvePath(dbName);
                    printToLog("Database resolved to path '"+file.nativePath+"'");
                    sqlConnection = new SQLConnection();
    
                    //open the database in synchronous mode to avoid complicating code with event handlers.
                    //alternatively use the openAsync function.
                    sqlConnection.open(file);
                    printToLog("Connection to database has been opened successfully.");
    
                    var sql:String = "CREATE TABLE IF NOT EXISTS my_table(id INTEGER PRIMARY KEY, title VARCHAR(100), width INTEGER, height INTEGER, imagedata BLOB)";
                    var createStatement:SQLStatement = new SQLStatement();
                    createStatement.sqlConnection = sqlConnection;
                    createStatement.text = sql;
                    try
                    {
                        printToLog("Executing sql statement:\n"+sql);
                        createStatement.execute();
                        printToLog("Success.");
                    }
                    catch(err:SQLError)
                    {
                        printToLog(err.message + " Details: " + err.details);
                    }
                }
    
                public function saveImage():void
                {
                    //create some dummy parameters for now
                    var id:int = 1;
                    var imageTitle:String = "Test Image";
                    var imageToSave:Image = remoteImage;
    
                    // The JPEGEncoder and PNGEncoder allow you to convert BitmapData object into a ByteArray,
                    //ready for storage in an SQLite blob field
                    var encoder:JPEGEncoder = new JPEGEncoder(75);  //quality of compression. 75 is a good compromise
                    //var encoder:PNGEncoder = new PNGEncoder();
                    var imageByteArray:ByteArray = encoder.encode(imageToSave.bitmapData);
    
                    //insert data to db
                    var insertStatement:SQLStatement = new SQLStatement();
                    insertStatement.sqlConnection = sqlConnection;
                    insertStatement.text = "INSERT INTO my_table (id, title, width, height, imagedata) VALUES (@id, @title, @width, @height, @imageByteArray)";
                    insertStatement.parameters["@id"] = id; // Integer with id
                    insertStatement.parameters["@title"] = imageTitle; // String containing title
    
                    //also save width and height of image so you can recreate the image when you get it out of the db.
                    //NOTE: the width and height will be those of the originally loaded image,
                    //      even if you explicitly set width and height on your Image instance.
                    insertStatement.parameters["@width"] = imageToSave.bitmapData.width;
                    insertStatement.parameters["@height"] = imageToSave.bitmapData.height;
    
                    // Encode the ByteArray into a base64 string, otherwise it won't work when reading it back in
                    var baseEncoder:Base64Encoder = new Base64Encoder();
                    baseEncoder.encodeBytes(imageByteArray);
                    var encodedBytes:String = baseEncoder.toString();
                    insertStatement.parameters["@imageByteArray"] = encodedBytes; // ByteArray containing image
                    try
                    {
                        printToLog("Executing sql statement:\n"+insertStatement.text);
                        printToLog("id="+id);
                        printToLog("title="+imageTitle);
                        printToLog("imageByteArray="+imageByteArray);
                        insertStatement.execute();
                        printToLog("Success.");
                    }
                    catch(err:SQLError)
                    {
                        printToLog(err.message + " Details: " + err.details);
                    }
                }
    
                public function loadImage():void
                {
                    //select data from db
                    var selectStatement:SQLStatement = new SQLStatement();
                    selectStatement.sqlConnection = sqlConnection;
                    selectStatement.text = "SELECT title, width, height, imagedata FROM my_table WHERE id = @id;";
                    selectStatement.parameters["@id"] = 1; // Id of target record
                    try
                    {
                        printToLog("Executing sql statement:\n"+selectStatement.text);
                        selectStatement.execute();
                        printToLog("Success.");
                    }
                    catch(err:SQLError)
                    {
                        printToLog(err.message + " Details: " + err.details);
                        return;
                    }
    
                    //parse results
                    var result:SQLResult = selectStatement.getResult();
                    if (result.data != null)
                    {
                        var row:Object = result.data[0];
    
                        var title:String = result.data[0].title;
                        var width:int = result.data[0].width;
                        var height:int = result.data[0].height;
    
                        //read the image data as a base64 encoded String, then decode it into a ByteArray
                        var encodedBytes:String = result.data[0].imagedata;
                        var baseDecoder:Base64Decoder = new Base64Decoder();
                        baseDecoder.decode(encodedBytes);
                        var byteArray:ByteArray = baseDecoder.toByteArray();
    
                        //assign the ByteArray to the image source
                        savedImage.width = width;
                        savedImage.height = height;
                        savedImage.source = byteArray;
                    }
                }
    
                //This is just a quick test method to see how we can pull out the
                //original ByteArray without passing through the DB
                public function copyImage():void
                {
                    //var imageByteArray:ByteArray = remoteImage.loaderInfo.bytes;
                    //This throws the following error:
                    //Error #3226: Cannot import a SWF file when LoaderContext.allowCodeImport is false.
                    //That's too bad because it would save a lot of time encoding the same bytes we
                    //already have (not to mention the loss of quality if we compress JPEG less than 100).
    
                    //This is the only solution I've found so far, but slows everything up
                    var encoder:JPEGEncoder = new JPEGEncoder(75);
                    //var encoder:PNGEncoder = new PNGEncoder();  -- alternative encoder: huge files
                    var imageByteArray:ByteArray = encoder.encode(remoteImage.bitmapData);
    
                    savedImage.source = imageByteArray;
                }
    
                public function printToLog(msg:String):void
                {
                    logOutput.appendText(msg + "\n");
                    StyleableTextField(logOutput.textDisplay).scrollV++;  //this is to scroll automatically when text is added.
                }
            ]]>
        </fx:Script>
    </s:View>
    

    最佳答案

    这篇文章的底部有一个很好的方法
    http://blog.affirmix.com/2009/01/28/getting-started-with-adobe-air-and-sqlite-and-avoiding-the-problems/

    您可能还需要考虑阅读评论,因为有人提到在阅读时提交和解码之前通过将其编码为 base64 来避免错误。

    为后人着想:

    这将需要成为应用程序代码的一部分

            import flash.display.Bitmap;
        import flash.display.Loader;
        import flash.filesystem.File;
        import flash.net.URLLoader;
        import flash.utils.ByteArray;
        import mx.graphics.codec.PNGEncoder;
    
        private function selectPicture():void
        {
            // This little section here creates a file object, and then launches the file browser so that you can select your image
            var file:File = File.documentsDirectory;
            file.addEventListener(Event.SELECT, handleSelectPicture);
            file.browseForOpen("Select Picture");
        }
    
        private function handleSelectPicture(event:Event):void
        {
            // Once the image file has been selected, we now have to load it
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoadPicture);
            loader.load(new URLRequest(event.target.url));
        }
    
        private function handleLoadPicture(event:Event):void
        {
            // The first thing that we do is create a Loader object (which is a subclass od DisplayObject)
            var loader:Loader = Loader(event.target.loader);
            // Next, we cast the loader as a Bitmpa object, as the Bitmap object has function to return a BitmapData object based on the image
            var image:Bitmap = Bitmap(loader.content);
            var encoder:PNGEncoder = new PNGEncoder();
            // The PNGEncoder allows you to convert BitmapData object into a ByteArray, ready for storage in an SQLite blob field
            var byteArray:ByteArray = encoder.encode(image.bitmapData);
    
            var statement:SQLStatement = SQLConnectionWrapper.instance.setPicture(1, byteArray);
            statement.execute(-1, responder);
        }
    

    这将需要成为 SQLConnectionWrapper 的一部分
        private function setPicture(recordId:String, byteArray:ByteArray):void
        {
            if(!(insertRecord is SQLStatement)){
                insertRecord = new SQLStatement();
                insertRecord.sqlConnection = connection;
                insertRecord.text = "INSERT INTO picture_tbl (record_id, data) VALUES (:recordId, :byteArray)";
            }
            insertRecord.parameters[":recordId"] = recordId;
            // The ByteArray should be added as a parameter; this makes the whole process of storing the image in the blob field very easy
            insertRecord.parameters[":byteArray"] = byteArray;
    
            return insertRecord;
        }
    

    这将需要成为应用程序代码的一部分
        import mx.controls.Image;
    
        // This function would be defined in a Responder object that handles a successful query of picture_tbl
        private function handleSuccess(result:SQLResult):void
        {
            var image:Image = new Image();
            image.addEventListener(Event.COMPLETE, handleLoadPicture);
            image.load(result.data[0].picture);
        }
    
        private function handleLoadPicture(event:Event):void
        {
            var picture:DisplayObject = DisplayObject(event.target.content);
        }
    

    按照要求:
    private var myCoverArtLoader:URLLoader;
    
                private function set_coverArt(evt:Event) : void {
                coverArtImage = new Image();
                var ba:ByteArray = new ByteArray();
                ba = myCoverArtLoader.data;
    
                coverArtImage.source = ba;
                myCoverArtLoader.removeEventListener(Event.COMPLETE, set_coverArt);
    
                var byteArray:ByteArray = new ByteArray;
                byteArray = ba;
    
                var sql:String;
                sql = "UPDATE random SET coverArtImage=@cover " +
                      "WHERE id = @id";
                var stmt:SQLStatement = new SQLStatement();
                stmt.sqlConnection = sqlConnection;
                stmt.text = sql;
                stmt.parameters["@cover"] = byteArray;
                stmt.parameters["@id"] = data.id;
                stmt.execute();
            }
    

    然后加载它:
                private function select_fromDatabase() : void {
                var sql:String = "SELECT coverArtImage FROM random WHERE id = '" + data.id + "'";
                stmt = new SQLStatement();
                stmt.sqlConnection = sqlConnection;
                stmt.text = sql;
    
                stmt.addEventListener(SQLEvent.RESULT, handleSuccess);
    
                stmt.execute();
            }
                private function handleSuccess(evt:SQLEvent): void {
                var result:SQLResult = evt.currentTarget.getResult();
    
                if (result.data[0].coverArtImage == null) {
                    get_cover_xml();
                } else {
                    get_cover_db(result);
                }
    
                stmt.removeEventListener(SQLEvent.RESULT, handleSuccess);
            }
                private function get_cover_db(result:SQLResult) : void {
                var ba:ByteArray = new ByteArray();
                ba = result.data[0].coverArtImage;
                coverArtImage = new Image();
                coverArtImage.source = ba;
            }
    

    我希望这有帮助!

    关于apache-flex - 使用 Flex 4.5 将图像保存和加载到本地 SQLite BLOB,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7348318/

    10-16 22:12