2

任务

在 PowerShell 中,我想借助taglip-sharp库将图片添加为 ID3V2 标记。
通常你这样做:

# Load taglib-sharb library
[Reflection.Assembly]::LoadFrom( (Resolve-Path "..\Common\taglib-sharp.dll"))

# Load MP3 file
$media = [TagLib.File]::Create("C:\MusicFile.mp3")

# Load picture
$pic = [taglib.picture]::createfrompath("C:\MyAlbumArt.jpg")

# Add picture to MP3
$media.Tag.Pictures = $pic

# Save Mp3 
$media.Save() 

一般问题

仅当您的图片是位于本地某处的文件时,上述方法才有效。但是我有一张图片作为[System.Drawing.Bitmap]对象,它没有文件路径来加载它createfrompath

在你说然后把它写到光盘之前:我宁愿避免保存它们,因为我的最终脚本处理了许多图片和 mp3 文件。而且我不想写和删除数百张图片。

具体问题

我看到 taglib 还有另一种方法CreateFromFile(File.IFileAbstraction )来加载图片。但是如何将 a 转换[System.Drawing.Bitmap]为 a IFileAbstraction

我在网上找到的最接近的帮助是这里这里。但它适用于 .NET 4.5,我无法将其转换为 PowerShell 语法

如果有帮助,这里是 taglib-sharp 的图片对象的文档。

4

1 回答 1

2

简单的版本是在 powershell 中调用c# 代码(如此所述)

  $refs = @(
"c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Drawing.dll",
"d:\taglib-sharp.dll"
)

$Source = @"

 namespace YourNamespace
    {
        public class Helper
        {
            public static TagLib.IPicture[] GetPictureFromBitmap(System.Drawing.Bitmap img)
            {
                return

                    new TagLib.IPicture[]
                    {
                        new TagLib.Picture(
                            new TagLib.ByteVector(
                                (byte[]) new System.Drawing.ImageConverter().ConvertTo(img, typeof (byte[]))))
                    };

            }
        }
    }
"@ 

Add-Type -Path $refs
Add-Type -ReferencedAssemblies $refs -TypeDefinition $Source -Language CSharp  

# Load MP3 file
$media = [TagLib.File]::Create("C:\MusicFile.mp3")

# Load picture into System.Drawing.Image
[Bitmap]$pic =[System.Drawing.Image]::FromFile("C:\MyAlbumArt.jpg")

# Add picture to MP3
$media.Tag.Pictures = [YourNamespace.Helper]::GetPictureFromBitmap($pic)

# Save Mp3 
$media.Save() 

完整的 powershell 版本:

function GetPictureFromBitmap([System.Drawing.Bitmap]$bitmap)
{
    $converter = New-Object -TypeName System.Drawing.ImageConverter
    $byte_vec = New-Object -TypeName TagLib.ByteVector -ArgumentList $converter.ConvertTo($bitmap, [byte[]])
    $picture = New-Object -TypeName TagLib.Picture -ArgumentList $byte_vec
    $picture_list = New-Object TagLib.IPicture[] 1
    $picture_list[0] = $picture
    return $picture_list
}


$refs = @(
"c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Drawing.dll",
"d:\taglib-sharp.dll"
)

Add-Type -Path $refs

# Load MP3 file
$media = [TagLib.File]::Create("C:\MusicFile.mp3")

# Load picture into System.Drawing.Image
[Bitmap]$pic = [System.Drawing.Image]::FromFile("C:\MyAlbumArt.jpg")

# Add picture to MP3
$media.Tag.Pictures = GetPictureFromBitmap($pic)

# Save Mp3 
$media.Save() 

在 powershell v3 中测试

于 2015-08-19T16:04:23.870 回答