使用Flex 4.5将映像保存并加载到本地SQLite BLOB

时间:2011-09-08 12:52:13

标签: flex flex4 flex4.5

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

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

到目前为止,最大的问题是:在哪里可以获得加载图像的ByteArray?我已经尝试过调试和检查Image,BitmapImage和BitMapData,但是没有字节数组的迹象....也许它在ContentLoader中?但除非我启用缓存,否则它为空。

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

一旦完全正常运作,我只会将此问题标记为已回答。

更新SEPT。 09年2011年:

以下代码现在可以在两个方向上完全正常运行(保存和加载)。以下是我学到的一些内容:

  • 事实证明,火花图像的ByteArray可以在图像本身的LoaderInfo中找到。像这样:
  

image.loaderInfo.bytes

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

错误#3226:无法导入SWF文件   LoaderContext.allowCodeImport为false。

  • 这太糟糕了,因为它会节省很多时间和处理能力。 如果有人知道如何解决此错误,我们将非常感谢!

  • 无论如何,解决方法是使用JPEGEncoder或PNGEncoder对ByteArray进行编码。我使用JPEGEncoder生成更小的文件。方法如下:

var encoder:JPEGEncoder = new JPEGEncoder(75);  
var imageByteArray:ByteArray = encoder.encode(imageToSave.bitmapData);
  • 现在问题是将这些字节保存到数据库中。一旦我们将它们读出来,现在保存它们将无法工作,我不知道为什么。因此,解决方案是将它们编码为base64字符串,如下所示:
var baseEncoder:Base64Encoder = new Base64Encoder();
baseEncoder.encodeBytes(imageByteArray); 
var encodedBytes:String = baseEncoder.toString();
  • 所以现在只需将该字符串保存到BLOB字段中,然后将其读出。但是,您必须将它从base64字符串解码为ByteArray,如下所示:
var encodedBytes:String = result.data[0].imagedata;
var baseDecoder:Base64Decoder = new Base64Decoder();
baseDecoder.decode(encodedBytes);
var byteArray:ByteArray = baseDecoder.toByteArray();
  • 现在将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>

2 个答案:

答案 0 :(得分:4)

本文的底部有一个很好的方法 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;
        }

我希望有所帮助!

答案 1 :(得分:0)

我相信你错过了一些事情:

你不能像这样使图像源成为ByteArray。我已成功使用URLloader类从SQLite插入的图像中检索ByteArray:

    var pic1:ByteArray;
    var l:URLLoader = new URLLoader(new URLRequest(event.target.url)); 
    l.dataFormat = URLLoaderDataFormat.BINARY;
    pic1 = event.currentTarget.data as ByteArray;

尝试一下,然后根据需要切换目标。