Files
img2mp3/README.md
2025-09-06 19:11:40 +02:00

9.0 KiB

IMG2MP3 🎵🖼️

A powerful Node.js tool for encoding MP3 files into images and decoding them back, with a built-in player for audio-embedded images.

Features

  • 🔐 Steganography: Hide MP3 files inside images using advanced encoding techniques
  • 🎵 Audio Player: Built-in player for .i2m files with support for multiple audio backends
  • 🖼️ Image Support: Works with various image formats (PNG, JPEG, WebP, etc.)
  • CLI Interface: Easy-to-use command-line interface with interactive mode
  • 📊 File Analysis: Get detailed information about encoded files
  • 🧹 Clean API: Simple programmatic interface for integration into other projects

Installation

npm install -g img2mp3

Local Installation

npm install img2mp3

Usage

Command Line Interface

Encode MP3 into Image

# Basic encoding
img2mp3 encode image.jpg song.mp3

# Specify output file
img2mp3 encode image.jpg song.mp3 output.i2m

# Verbose output
img2mp3 encode image.jpg song.mp3 -v

Decode .i2m File

# Extract both image and MP3
img2mp3 decode song.i2m

# Specify output paths
img2mp3 decode song.i2m -i extracted_image.png -m extracted_song.mp3

Play .i2m File

# Play audio from image
img2mp3 play song.i2m

# Play with verbose output
img2mp3 play song.i2m -v

Get File Information

# Show detailed information about .i2m file
img2mp3 info song.i2m

Interactive Mode

# Start interactive mode for guided usage
img2mp3 interactive
# or
img2mp3 i

Programmatic Usage

const { IMG2MP3, encode, decode, play } = require('img2mp3');

// Using the main class
const img2mp3 = new IMG2MP3();

// Encode MP3 into image
async function encodeExample() {
  try {
    const result = await img2mp3.encode('image.jpg', 'song.mp3', 'output.i2m');
    console.log('Encoding successful:', result);
  } catch (error) {
    console.error('Encoding failed:', error.message);
  }
}

// Decode .i2m file
async function decodeExample() {
  try {
    const result = await img2mp3.decode('output.i2m', 'extracted.png', 'extracted.mp3');
    console.log('Decoding successful:', result);
  } catch (error) {
    console.error('Decoding failed:', error.message);
  }
}

// Play .i2m file
async function playExample() {
  try {
    await img2mp3.play('output.i2m');
    console.log('Playback finished');
  } catch (error) {
    console.error('Playback failed:', error.message);
  }
}

// Get file information
async function infoExample() {
  try {
    const info = await img2mp3.getInfo('output.i2m');
    if (info.isValid) {
      console.log('File info:', info);
    } else {
      console.error('Invalid file:', info.error);
    }
  } catch (error) {
    console.error('Analysis failed:', error.message);
  }
}

// Using convenience functions
async function quickExample() {
  // Quick encode
  await encode('image.jpg', 'song.mp3', 'quick.i2m');
  
  // Quick decode
  await decode('quick.i2m', 'quick_img.png', 'quick_song.mp3');
  
  // Quick play
  await play('quick.i2m');
}

How It Works

IMG2MP3 uses advanced steganography techniques to embed MP3 data into images:

  1. Encoding Process:

    • Reads the source image and MP3 file
    • Creates a header with magic bytes and metadata
    • Combines header + original image + MP3 data
    • Generates a new container image to hold all data
    • Saves as .i2m file (Image-to-MP3 format)
  2. Decoding Process:

    • Reads the .i2m file
    • Verifies magic bytes to ensure valid format
    • Extracts header information
    • Separates original image and MP3 data
    • Saves extracted files
  3. Playback Process:

    • Extracts MP3 data to temporary file
    • Uses system audio players for playback
    • Cleans up temporary files automatically

Audio Player Support

The built-in player supports multiple audio backends:

  • mpg123 (Recommended for MP3)
  • mpv (Universal media player)
  • ffplay (FFmpeg player)
  • cvlc (VLC command-line)
  • play (SOX audio player)

The tool automatically detects available players and uses the best one.

Installing Audio Players

Ubuntu/Debian:

sudo apt-get install mpg123 mpv ffmpeg vlc sox

macOS (with Homebrew):

brew install mpg123 mpv ffmpeg vlc sox

Windows:

File Format (.i2m)

The .i2m (Image-to-MP3) format is a custom container that preserves both the original image and embedded MP3:

[Header - 16 bytes]
├── Magic bytes: "I2M3" (4 bytes)
├── MP3 size: uint32 (4 bytes)
├── Original image size: uint32 (4 bytes)
└── Image width: uint32 (4 bytes)

[Original Image Data]
├── Complete original image file
└── Preserves original format and quality

[MP3 Data]
├── Complete MP3 file
└── Preserves original audio quality

[Container Image]
├── PNG format for reliable pixel manipulation
└── Visually appears as a normal image

API Reference

IMG2MP3 Class

Constructor

const img2mp3 = new IMG2MP3();

Methods

encode(imagePath, mp3Path, outputPath)

Encodes MP3 data into an image.

Parameters:

  • imagePath (string): Path to source image
  • mp3Path (string): Path to MP3 file
  • outputPath (string): Path for output .i2m file

Returns: Promise<Object> with encoding results

decode(i2mPath, outputImagePath, outputMp3Path)

Decodes .i2m file back to image and MP3.

Parameters:

  • i2mPath (string): Path to .i2m file
  • outputImagePath (string): Path for extracted image
  • outputMp3Path (string): Path for extracted MP3

Returns: Promise<Object> with decoding results

getInfo(i2mPath)

Gets information about .i2m file.

Parameters:

  • i2mPath (string): Path to .i2m file

Returns: Promise<Object> with file information

play(i2mPath, options)

Plays audio from .i2m file.

Parameters:

  • i2mPath (string): Path to .i2m file
  • options (Object): Playback options (optional)

Returns: Promise<void>

stop()

Stops current playback.

getPlaybackStatus()

Gets current playback status.

Returns: Object with playback information

cleanup()

Cleans up temporary files.

Examples

Basic Example

const { IMG2MP3 } = require('img2mp3');

async function example() {
  const img2mp3 = new IMG2MP3();
  
  // Encode
  console.log('Encoding...');
  await img2mp3.encode('photo.jpg', 'music.mp3', 'hidden.i2m');
  
  // Get info
  const info = await img2mp3.getInfo('hidden.i2m');
  console.log(`Embedded ${info.mp3Size} bytes of audio`);
  
  // Play
  console.log('Playing...');
  await img2mp3.play('hidden.i2m');
  
  // Decode
  console.log('Extracting...');
  await img2mp3.decode('hidden.i2m', 'restored.jpg', 'restored.mp3');
}

example().catch(console.error);

Batch Processing

const fs = require('fs');
const path = require('path');
const { encode } = require('img2mp3');

async function batchEncode() {
  const imageDir = './images';
  const audioDir = './audio';
  const outputDir = './encoded';
  
  const images = fs.readdirSync(imageDir).filter(f => 
    f.endsWith('.jpg') || f.endsWith('.png')
  );
  
  const audioFiles = fs.readdirSync(audioDir).filter(f => 
    f.endsWith('.mp3')
  );
  
  for (let i = 0; i < Math.min(images.length, audioFiles.length); i++) {
    const imagePath = path.join(imageDir, images[i]);
    const audioPath = path.join(audioDir, audioFiles[i]);
    const outputPath = path.join(outputDir, `encoded_${i}.i2m`);
    
    try {
      console.log(`Encoding ${images[i]} + ${audioFiles[i]}...`);
      await encode(imagePath, audioPath, outputPath);
      console.log(`✓ Created ${outputPath}`);
    } catch (error) {
      console.error(`✗ Failed to encode ${images[i]}: ${error.message}`);
    }
  }
}

batchEncode();

Requirements

  • Node.js: >= 14.0.0
  • System: Linux, macOS, or Windows
  • Audio Player: At least one supported audio player for playback

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

v1.0.0

  • Initial release
  • MP3 encoding/decoding in images
  • Built-in audio player
  • CLI interface with interactive mode
  • Cross-platform support

Support

If you encounter any issues or have questions:

  1. Check the Issues page
  2. Create a new issue with detailed information
  3. Include your system information and error messages

Disclaimer

This tool is for educational and legitimate use cases only. Please respect copyright laws and only embed audio that you have the right to use.