Search code examples
dm-script

How to get an image from a long string data in dm-script


I would like to get an image data from a string data array. The below script runs well but speed is low. (The actual length of the string data is much longer than in the example below.) I guess pixel addressing in the for loop would take a time.

image str2img(string str)
{
    image img:=RealImage("",4,10,1)
    string tempstr=str
    for(number i=0;i<10;i++)
    {
        if(find(tempstr,",")!=-1)
        {
            img[i,0]=tempstr.left(find(tempstr,",")).val()
            tempstr=tempstr.right(tempstr.len()-find(tempstr,",")-1)
            result(tempstr+"\n")
        }else
        {
            img[i,0]=tempstr.val()
        }
    }
    return img
}

string input="1,2,3,4,5,6,7,8,9,10"
image output=str2img(input)
output.showimage()

Then I wrote the following script to use stream. However I got the error massage 'Non-numeric text encountered'.

image str2img(string str)
{
    TagGroup Tg=NewTagGroup()
    Tg.TagGroupSetTagAsString("data",str)
    
    object fstream=NewStreamFromBuffer(0)
    TagGroupWriteTagDataToStream(Tg,"data",fstream,0)
    fstream.StreamSetPos(0,0)

    number bLinesAreRows=1
    number bSizeByCount=1 
    number dtype=2 //2 for real4 (float)
    object imgSizeObj = Alloc( "ImageData_ImageDataSize" )
    image img := ImageImportTextData( "Imag Name " , fstream , dtype , imgSizeObj , bLinesAreRows , bSizeByCount )
    return img
}

string input="1,2,3,4,5,6,7,8,9,10"
image output=str2img(input)
output.showimage()

Is the "ImageImportTextData()" function valid only for reading a saved file?

Or are there any efficient way to obtain an image from a long string data?


Solution

  • Very good question and I like they way you were going about it. No, ImageImportTextData() works for any stream as you will see in the example below. However, the command requires text-lines to be finalized by line-breaks if you want it to count, and there seems to be an issue with String-tags streaming. I never use this, as there are dedicated commands to stream text.

    So, your fixed script looks like:


    image str2img(string str)
    {
        object fstream=NewStreamFromBuffer(0)
        fStream.StreamWriteAsText(0,str)  // Write text to stream directly
        fstream.StreamSetPos(0,0)
    
        number bLinesAreRows=1
        number bSizeByCount=1 
        number dtype=2 //2 for real4 (float)
        object imgSizeObj = Alloc( "ImageData_ImageDataSize" )
        
        image img := ImageImportTextData( "Imag Name " , fstream , dtype , imgSizeObj , bLinesAreRows , bSizeByCount )
        return img
    }
    
    string input="1,2,3,4,5,6,7,8,9,10\n" // Note final line-break if you want to count.
    image output=str2img(input)
    output.showimage()